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 | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a named type symbol whose members are declared in source.
/// </summary>
internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol
{
// The flags type is used to compact many different bits of information efficiently.
private struct Flags
{
// We current pack everything into one 32-bit int; layout is given below.
//
// | |vvv|zzzz|f|d|yy|wwwwww|
//
// w = special type. 6 bits.
// y = IsManagedType. 2 bits.
// d = FieldDefinitionsNoted. 1 bit
// f = FlattenedMembersIsSorted. 1 bit.
// z = TypeKind. 4 bits.
// v = NullableContext. 3 bits.
private int _flags;
private const int SpecialTypeOffset = 0;
private const int SpecialTypeSize = 6;
private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize;
private const int ManagedKindSize = 2;
private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize;
private const int FieldDefinitionsNotedSize = 1;
private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize;
private const int FlattenedMembersIsSortedSize = 1;
private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize;
private const int TypeKindSize = 4;
private const int NullableContextOffset = TypeKindOffset + TypeKindSize;
private const int NullableContextSize = 3;
private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1;
private const int ManagedKindMask = (1 << ManagedKindSize) - 1;
private const int TypeKindMask = (1 << TypeKindSize) - 1;
private const int NullableContextMask = (1 << NullableContextSize) - 1;
private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset;
private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset;
public SpecialType SpecialType
{
get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); }
}
public ManagedKind ManagedKind
{
get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); }
}
public bool FieldDefinitionsNoted
{
get { return (_flags & FieldDefinitionsNotedBit) != 0; }
}
// True if "lazyMembersFlattened" is sorted.
public bool FlattenedMembersIsSorted
{
get { return (_flags & FlattenedMembersIsSortedBit) != 0; }
}
public TypeKind TypeKind
{
get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); }
}
#if DEBUG
static Flags()
{
// Verify masks are sufficient for values.
Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask));
Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask));
}
#endif
public Flags(SpecialType specialType, TypeKind typeKind)
{
int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset;
int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset;
_flags = specialTypeInt | typeKindInt;
}
public void SetFieldDefinitionsNoted()
{
ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit);
}
public void SetFlattenedMembersIsSorted()
{
ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit));
}
private static bool BitsAreUnsetOrSame(int bits, int mask)
{
return (bits & mask) == 0 || (bits & mask) == mask;
}
public void SetManagedKind(ManagedKind managedKind)
{
int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset;
Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet));
ThreadSafeFlagOperations.Set(ref _flags, bitsToSet);
}
public bool TryGetNullableContext(out byte? value)
{
return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value);
}
public bool SetNullableContext(byte? value)
{
return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset));
}
}
private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary =
PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer);
protected SymbolCompletionState state;
private Flags _flags;
private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics;
private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies;
private readonly DeclarationModifiers _declModifiers;
private readonly NamespaceOrTypeSymbol _containingSymbol;
protected readonly MergedTypeDeclaration declaration;
// The entry point symbol (resulting from top-level statements) is needed to construct non-type members because
// it contributes to their binders, so we have to compute it first.
// The value changes from "default" to "real value". The transition from "default" can only happen once.
private ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> _lazySimpleProgramEntryPoints;
// To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set)
// The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once.
private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel;
private MembersAndInitializers? _lazyMembersAndInitializers;
private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary;
private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary;
private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance);
private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers;
private ImmutableArray<Symbol> _lazyMembersFlattened;
private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations;
private int _lazyKnownCircularStruct;
private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized;
private ThreeState _lazyContainsExtensionMethods;
private ThreeState _lazyAnyMemberHasAttributes;
#region Construction
internal SourceMemberContainerTypeSymbol(
NamespaceOrTypeSymbol containingSymbol,
MergedTypeDeclaration declaration,
BindingDiagnosticBag diagnostics,
TupleExtraData? tupleData = null)
: base(tupleData)
{
// If we're dealing with a simple program, then we must be in the global namespace
Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram));
_containingSymbol = containingSymbol;
this.declaration = declaration;
TypeKind typeKind = declaration.Kind.ToTypeKind();
var modifiers = MakeModifiers(typeKind, diagnostics);
foreach (var singleDeclaration in declaration.Declarations)
{
diagnostics.AddRange(singleDeclaration.Diagnostics);
}
int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask);
if ((access & (access - 1)) != 0)
{ // more than one access modifier
if ((modifiers & DeclarationModifiers.Partial) != 0)
diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this);
access = access & ~(access - 1); // narrow down to one access modifier
modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all
modifiers |= (DeclarationModifiers)access; // except the one
}
_declModifiers = modifiers;
var specialType = access == (int)DeclarationModifiers.Public
? MakeSpecialType()
: SpecialType.None;
_flags = new Flags(specialType, typeKind);
var containingType = this.ContainingType;
if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected())
{
diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this);
}
state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately
}
private SpecialType MakeSpecialType()
{
// check if this is one of the COR library types
if (ContainingSymbol.Kind == SymbolKind.Namespace &&
ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes)
{
//for a namespace, the emitted name is a dot-separated list of containing namespaces
var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat);
emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName);
return SpecialTypes.GetTypeFromMetadataName(emittedName);
}
else
{
return SpecialType.None;
}
}
private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics)
{
Symbol containingSymbol = this.ContainingSymbol;
DeclarationModifiers defaultAccess;
var allowedModifiers = DeclarationModifiers.AccessibilityMask;
if (containingSymbol.Kind == SymbolKind.Namespace)
{
defaultAccess = DeclarationModifiers.Internal;
}
else
{
allowedModifiers |= DeclarationModifiers.New;
if (((NamedTypeSymbol)containingSymbol).IsInterface)
{
defaultAccess = DeclarationModifiers.Public;
}
else
{
defaultAccess = DeclarationModifiers.Private;
}
}
switch (typeKind)
{
case TypeKind.Class:
case TypeKind.Submission:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract
| DeclarationModifiers.Unsafe;
if (!this.IsRecord)
{
allowedModifiers |= DeclarationModifiers.Static;
}
break;
case TypeKind.Struct:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe;
if (!this.IsRecordStruct)
{
allowedModifiers |= DeclarationModifiers.Ref;
}
break;
case TypeKind.Interface:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe;
break;
case TypeKind.Delegate:
allowedModifiers |= DeclarationModifiers.Unsafe;
break;
}
bool modifierErrors;
var mods = MakeAndCheckTypeModifiers(
defaultAccess,
allowedModifiers,
diagnostics,
out modifierErrors);
this.CheckUnsafeModifier(mods, diagnostics);
if (!modifierErrors &&
(mods & DeclarationModifiers.Abstract) != 0 &&
(mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0)
{
diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this);
}
if (!modifierErrors &&
(mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static))
{
diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this);
}
switch (typeKind)
{
case TypeKind.Interface:
mods |= DeclarationModifiers.Abstract;
break;
case TypeKind.Struct:
case TypeKind.Enum:
mods |= DeclarationModifiers.Sealed;
break;
case TypeKind.Delegate:
mods |= DeclarationModifiers.Sealed;
break;
}
return mods;
}
private DeclarationModifiers MakeAndCheckTypeModifiers(
DeclarationModifiers defaultAccess,
DeclarationModifiers allowedModifiers,
BindingDiagnosticBag diagnostics,
out bool modifierErrors)
{
modifierErrors = false;
var result = DeclarationModifiers.Unset;
var partCount = declaration.Declarations.Length;
var missingPartial = false;
for (var i = 0; i < partCount; i++)
{
var decl = declaration.Declarations[i];
var mods = decl.Modifiers;
if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0)
{
missingPartial = true;
}
if (!modifierErrors)
{
mods = ModifierUtils.CheckModifiers(
mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics,
modifierTokens: null, modifierErrors: out modifierErrors);
// It is an error for the same modifier to appear multiple times.
if (!modifierErrors)
{
var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false);
if (info != null)
{
diagnostics.Add(info, this.Locations[0]);
modifierErrors = true;
}
}
}
if (result == DeclarationModifiers.Unset)
{
result = mods;
}
else
{
result |= mods;
}
}
if ((result & DeclarationModifiers.AccessibilityMask) == 0)
{
result |= defaultAccess;
}
if (missingPartial)
{
if ((result & DeclarationModifiers.Partial) == 0)
{
// duplicate definitions
switch (this.ContainingSymbol.Kind)
{
case SymbolKind.Namespace:
for (var i = 1; i < partCount; i++)
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol);
modifierErrors = true;
}
break;
case SymbolKind.NamedType:
for (var i = 1; i < partCount; i++)
{
if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial())
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name);
modifierErrors = true;
}
break;
}
}
else
{
for (var i = 0; i < partCount; i++)
{
var singleDeclaration = declaration.Declarations[i];
var mods = singleDeclaration.Modifiers;
if ((mods & DeclarationModifiers.Partial) == 0)
{
diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name);
modifierErrors = true;
}
}
}
}
if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword))
{
foreach (var syntaxRef in SyntaxReferences)
{
SyntaxToken? identifier = syntaxRef.GetSyntax() switch
{
BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier,
DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier,
_ => null
};
ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None);
}
}
return result;
}
internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location)
{
if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) &&
compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion())
{
diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name);
}
}
#endregion
#region Completion
internal sealed override bool RequiresCompletion
{
get { return true; }
}
internal sealed override bool HasComplete(CompletionPart part)
{
return state.HasComplete(part);
}
protected abstract void CheckBase(BindingDiagnosticBag diagnostics);
protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics);
internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken)
{
while (true)
{
// NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers.
cancellationToken.ThrowIfCancellationRequested();
var incompletePart = state.NextIncompletePart;
switch (incompletePart)
{
case CompletionPart.Attributes:
GetAttributes();
break;
case CompletionPart.StartBaseType:
case CompletionPart.FinishBaseType:
if (state.NotePartComplete(CompletionPart.StartBaseType))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
CheckBase(diagnostics);
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.FinishBaseType);
diagnostics.Free();
}
break;
case CompletionPart.StartInterfaces:
case CompletionPart.FinishInterfaces:
if (state.NotePartComplete(CompletionPart.StartInterfaces))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
CheckInterfaces(diagnostics);
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.FinishInterfaces);
diagnostics.Free();
}
break;
case CompletionPart.EnumUnderlyingType:
var discarded = this.EnumUnderlyingType;
break;
case CompletionPart.TypeArguments:
{
var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments
}
break;
case CompletionPart.TypeParameters:
// force type parameters
foreach (var typeParameter in this.TypeParameters)
{
typeParameter.ForceComplete(locationOpt, cancellationToken);
}
state.NotePartComplete(CompletionPart.TypeParameters);
break;
case CompletionPart.Members:
this.GetMembersByName();
break;
case CompletionPart.TypeMembers:
this.GetTypeMembersUnordered();
break;
case CompletionPart.SynthesizedExplicitImplementations:
this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked
break;
case CompletionPart.StartMemberChecks:
case CompletionPart.FinishMemberChecks:
if (state.NotePartComplete(CompletionPart.StartMemberChecks))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
AfterMembersChecks(diagnostics);
AddDeclarationDiagnostics(diagnostics);
// We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members
DeclaringCompilation.SymbolDeclaredEvent(this);
var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks);
Debug.Assert(thisThreadCompleted);
diagnostics.Free();
}
break;
case CompletionPart.MembersCompleted:
{
ImmutableArray<Symbol> members = this.GetMembersUnordered();
bool allCompleted = true;
if (locationOpt == null)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
member.ForceComplete(locationOpt, cancellationToken);
}
}
else
{
foreach (var member in members)
{
ForceCompleteMemberByLocation(locationOpt, member, cancellationToken);
allCompleted = allCompleted && member.HasComplete(CompletionPart.All);
}
}
if (!allCompleted)
{
// We did not complete all members so we won't have enough information for
// the PointedAtManagedTypeChecks, so just kick out now.
var allParts = CompletionPart.NamedTypeSymbolWithLocationAll;
state.SpinWaitComplete(allParts, cancellationToken);
return;
}
EnsureFieldDefinitionsNoted();
// We've completed all members, so we're ready for the PointedAtManagedTypeChecks;
// proceed to the next iteration.
state.NotePartComplete(CompletionPart.MembersCompleted);
break;
}
case CompletionPart.None:
return;
default:
// This assert will trigger if we forgot to handle any of the completion parts
Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0);
// any other values are completion parts intended for other kinds of symbols
state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll);
break;
}
state.SpinWaitComplete(incompletePart, cancellationToken);
}
throw ExceptionUtilities.Unreachable;
}
internal void EnsureFieldDefinitionsNoted()
{
if (_flags.FieldDefinitionsNoted)
{
return;
}
NoteFieldDefinitions();
}
private void NoteFieldDefinitions()
{
// we must note all fields once therefore we need to lock
var membersAndInitializers = this.GetMembersAndInitializers();
lock (membersAndInitializers)
{
if (!_flags.FieldDefinitionsNoted)
{
var assembly = (SourceAssemblySymbol)ContainingAssembly;
Accessibility containerEffectiveAccessibility = EffectiveAccessibility();
foreach (var member in membersAndInitializers.NonTypeMembers)
{
FieldSymbol field;
if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer)
{
continue;
}
Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility;
if (fieldDeclaredAccessibility == Accessibility.Private)
{
// mark private fields as tentatively unassigned and unread unless we discover otherwise.
assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true);
}
else if (containerEffectiveAccessibility == Accessibility.Private)
{
// mark effectively private fields as tentatively unassigned unless we discover otherwise.
assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false);
}
else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal)
{
// mark effectively internal fields as tentatively unassigned unless we discover otherwise.
// NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly.
// See property SourceAssemblySymbol.UnusedFieldWarnings.
assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false);
}
}
_flags.SetFieldDefinitionsNoted();
}
}
}
#endregion
#region Containers
public sealed override NamedTypeSymbol? ContainingType
{
get
{
return _containingSymbol as NamedTypeSymbol;
}
}
public sealed override Symbol ContainingSymbol
{
get
{
return _containingSymbol;
}
}
#endregion
#region Flags Encoded Properties
public override SpecialType SpecialType
{
get
{
return _flags.SpecialType;
}
}
public override TypeKind TypeKind
{
get
{
return _flags.TypeKind;
}
}
internal MergedTypeDeclaration MergedDeclaration
{
get
{
return this.declaration;
}
}
internal sealed override bool IsInterface
{
get
{
// TypeKind is computed eagerly, so this is cheap.
return this.TypeKind == TypeKind.Interface;
}
}
internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var managedKind = _flags.ManagedKind;
if (managedKind == ManagedKind.Unknown)
{
var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly);
managedKind = base.GetManagedKind(ref managedKindUseSiteInfo);
ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty);
ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty);
_flags.SetManagedKind(managedKind);
}
if (useSiteInfo.AccumulatesDiagnostics)
{
ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics;
// Ensure we have the latest value from the field
useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics);
Debug.Assert(!useSiteDiagnostics.IsDefault);
useSiteInfo.AddDiagnostics(useSiteDiagnostics);
}
if (useSiteInfo.AccumulatesDependencies)
{
ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies;
// Ensure we have the latest value from the field
useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies);
Debug.Assert(!useSiteDependencies.IsDefault);
useSiteInfo.AddDependencies(useSiteDependencies);
}
return managedKind;
}
public override bool IsStatic => HasFlag(DeclarationModifiers.Static);
public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref);
public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly);
public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed);
public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract);
internal bool IsPartial => HasFlag(DeclarationModifiers.Partial);
internal bool IsNew => HasFlag(DeclarationModifiers.New);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0;
public override Accessibility DeclaredAccessibility
{
get
{
return ModifierUtils.EffectiveAccessibility(_declModifiers);
}
}
/// <summary>
/// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields.
/// </summary>
private Accessibility EffectiveAccessibility()
{
var result = DeclaredAccessibility;
if (result == Accessibility.Private) return Accessibility.Private;
for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType)
{
switch (container.DeclaredAccessibility)
{
case Accessibility.Private:
return Accessibility.Private;
case Accessibility.Internal:
result = Accessibility.Internal;
continue;
}
}
return result;
}
#endregion
#region Syntax
public override bool IsScriptClass
{
get
{
var kind = this.declaration.Declarations[0].Kind;
return kind == DeclarationKind.Script || kind == DeclarationKind.Submission;
}
}
public override bool IsImplicitClass
{
get
{
return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass;
}
}
internal override bool IsRecord
{
get
{
return this.declaration.Declarations[0].Kind == DeclarationKind.Record;
}
}
internal override bool IsRecordStruct
{
get
{
return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct;
}
}
public override bool IsImplicitlyDeclared
{
get
{
return IsImplicitClass || IsScriptClass;
}
}
public override int Arity
{
get
{
return declaration.Arity;
}
}
public override string Name
{
get
{
return declaration.Name;
}
}
internal override bool MangleName
{
get
{
return Arity > 0;
}
}
internal override LexicalSortKey GetLexicalSortKey()
{
if (!_lazyLexicalSortKey.IsInitialized)
{
_lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation));
}
return _lazyLexicalSortKey;
}
public override ImmutableArray<Location> Locations
{
get
{
return declaration.NameLocations.Cast<SourceLocation, Location>();
}
}
public ImmutableArray<SyntaxReference> SyntaxReferences
{
get
{
return this.declaration.SyntaxReferences;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return SyntaxReferences;
}
}
// This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences
internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken)
{
var declarations = declaration.Declarations;
if (IsImplicitlyDeclared && declarations.IsEmpty)
{
return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken);
}
foreach (var declaration in declarations)
{
cancellationToken.ThrowIfCancellationRequested();
var syntaxRef = declaration.SyntaxReference;
if (syntaxRef.SyntaxTree == tree &&
(!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value)))
{
return true;
}
}
return false;
}
#endregion
#region Members
/// <summary>
/// Encapsulates information about the non-type members of a (i.e. this) type.
/// 1) For non-initializers, symbols are created and stored in a list.
/// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are
/// stored with other initialized fields and properties from the same syntax tree with
/// the same static-ness.
/// </summary>
protected sealed class MembersAndInitializers
{
internal readonly ImmutableArray<Symbol> NonTypeMembers;
internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers;
internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers;
internal readonly bool HaveIndexers;
internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields;
internal readonly bool IsNullableEnabledForStaticConstructorsAndFields;
public MembersAndInitializers(
ImmutableArray<Symbol> nonTypeMembers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers,
bool haveIndexers,
bool isNullableEnabledForInstanceConstructorsAndFields,
bool isNullableEnabledForStaticConstructorsAndFields)
{
Debug.Assert(!nonTypeMembers.IsDefault);
Debug.Assert(!staticInitializers.IsDefault);
Debug.Assert(staticInitializers.All(g => !g.IsDefault));
Debug.Assert(!instanceInitializers.IsDefault);
Debug.Assert(instanceInitializers.All(g => !g.IsDefault));
Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol));
Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer()));
this.NonTypeMembers = nonTypeMembers;
this.StaticInitializers = staticInitializers;
this.InstanceInitializers = instanceInitializers;
this.HaveIndexers = haveIndexers;
this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields;
this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields;
}
}
internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers
{
get { return GetMembersAndInitializers().StaticInitializers; }
}
internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers
{
get { return GetMembersAndInitializers().InstanceInitializers; }
}
internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic)
{
if (IsScriptClass && !isStatic)
{
int aggregateLength = 0;
foreach (var declaration in this.declaration.Declarations)
{
var syntaxRef = declaration.SyntaxReference;
if (tree == syntaxRef.SyntaxTree)
{
return aggregateLength + position;
}
aggregateLength += syntaxRef.Span.Length;
}
throw ExceptionUtilities.Unreachable;
}
int syntaxOffset;
if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset))
{
return syntaxOffset;
}
if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start)
{
// With dynamic analysis instrumentation, the introducing declaration of a type can provide
// the syntax associated with both the analysis payload local of a synthesized constructor
// and with the constructor itself. If the synthesized constructor includes an initializer with a lambda,
// that lambda needs a closure that captures the analysis payload of the constructor,
// and the offset of the syntax for the local within the constructor is by definition zero.
return 0;
}
// an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one).
/// </summary>
internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset)
{
Debug.Assert(ctorInitializerLength >= 0);
var membersAndInitializers = GetMembersAndInitializers();
var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers;
if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength))
{
syntaxOffset = 0;
return false;
}
// |<-----------distanceFromCtorBody----------->|
// [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body]
// |<--preceding init len-->| ^
// position
int initializersLength = getInitializersLength(allInitializers);
int distanceFromInitializerStart = position - initializer.Syntax.Span.Start;
int distanceFromCtorBody =
initializersLength + ctorInitializerLength -
(precedingLength + distanceFromInitializerStart);
Debug.Assert(distanceFromCtorBody > 0);
// syntax offset 0 is at the start of the ctor body:
syntaxOffset = -distanceFromCtorBody;
return true;
static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree,
out FieldOrPropertyInitializer found, out int precedingLength)
{
precedingLength = 0;
foreach (var group in initializers)
{
if (!group.IsEmpty &&
group[0].Syntax.SyntaxTree == tree &&
position < group.Last().Syntax.Span.End)
{
// Found group of interest
var initializerIndex = IndexOfInitializerContainingPosition(group, position);
if (initializerIndex < 0)
{
break;
}
precedingLength += getPrecedingInitializersLength(group, initializerIndex);
found = group[initializerIndex];
return true;
}
precedingLength += getGroupLength(group);
}
found = default;
return false;
}
static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers)
{
int length = 0;
foreach (var initializer in initializers)
{
length += getInitializerLength(initializer);
}
return length;
}
static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index)
{
int length = 0;
for (var i = 0; i < index; i++)
{
length += getInitializerLength(initializers[i]);
}
return length;
}
static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
int length = 0;
foreach (var group in initializers)
{
length += getGroupLength(group);
}
return length;
}
static int getInitializerLength(FieldOrPropertyInitializer initializer)
{
// A constant field of type decimal needs a field initializer, so
// check if it is a metadata constant, not just a constant to exclude
// decimals. Other constants do not need field initializers.
if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant)
{
// ignore leading and trailing trivia of the node:
return initializer.Syntax.Span.Length;
}
return 0;
}
}
private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position)
{
// Search for the start of the span (the spans are non-overlapping and sorted)
int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos));
// Binary search returns non-negative result if the position is exactly the start of some span.
if (index >= 0)
{
return index;
}
// Otherwise, ~index is the closest span whose start is greater than the position.
// => Check if the preceding initializer span contains the position.
int precedingInitializerIndex = ~index - 1;
if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position))
{
return precedingInitializerIndex;
}
return -1;
}
public override IEnumerable<string> MemberNames
{
get
{
return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames;
}
}
internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered()
{
return GetTypeMembersDictionary().Flatten();
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance);
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
ImmutableArray<NamedTypeSymbol> members;
if (GetTypeMembersDictionary().TryGetValue(name, out members))
{
return members;
}
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity);
}
private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary()
{
if (_lazyTypeMembers == null)
{
var diagnostics = BindingDiagnosticBag.GetInstance();
if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null)
{
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.TypeMembers);
}
diagnostics.Free();
}
return _lazyTypeMembers;
}
private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics)
{
var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>();
try
{
foreach (var childDeclaration in declaration.Children)
{
var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics);
this.CheckMemberNameDistinctFromType(t, diagnostics);
var key = (t.Name, t.Arity);
SourceNamedTypeSymbol? other;
if (conflictDict.TryGetValue(key, out other))
{
if (Locations.Length == 1 || IsPartial)
{
if (t.IsPartial && other.IsPartial)
{
diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t);
}
else
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name);
}
}
}
else
{
conflictDict.Add(key, t);
}
symbols.Add(t);
}
if (IsInterface)
{
foreach (var t in symbols)
{
Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]);
}
}
Debug.Assert(s_emptyTypeMembers.Count == 0);
return symbols.Count > 0 ?
symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) :
s_emptyTypeMembers;
}
finally
{
symbols.Free();
}
}
private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics)
{
switch (this.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
if (member.Name == this.Name)
{
diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name);
}
break;
case TypeKind.Interface:
if (member.IsStatic)
{
goto case TypeKind.Class;
}
break;
}
}
internal override ImmutableArray<Symbol> GetMembersUnordered()
{
var result = _lazyMembersFlattened;
if (result.IsDefault)
{
result = GetMembersByName().Flatten(null); // do not sort.
ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result);
result = _lazyMembersFlattened;
}
return result.ConditionallyDeOrder();
}
public override ImmutableArray<Symbol> GetMembers()
{
if (_flags.FlattenedMembersIsSorted)
{
return _lazyMembersFlattened;
}
else
{
var allMembers = this.GetMembersUnordered();
if (allMembers.Length > 1)
{
// The array isn't sorted. Sort it and remember that we sorted it.
allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance);
ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers);
}
_flags.SetFlattenedMembersIsSorted();
return allMembers;
}
}
public sealed override ImmutableArray<Symbol> GetMembers(string name)
{
ImmutableArray<Symbol> members;
if (GetMembersByName().TryGetValue(name, out members))
{
return members;
}
return ImmutableArray<Symbol>.Empty;
}
/// <remarks>
/// For source symbols, there can only be a valid clone method if this is a record, which is a
/// simple syntax check. This will need to change when we generalize cloning, but it's a good
/// heuristic for now.
/// </remarks>
internal override bool HasPossibleWellKnownCloneMethod()
=> IsRecord;
internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name)
{
if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct)
{
return GetMembers(name);
}
return ImmutableArray<Symbol>.Empty;
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
if (this.TypeKind == TypeKind.Enum)
{
// For consistency with Dev10, emit value__ field first.
var valueField = ((SourceNamedTypeSymbol)this).EnumValueField;
RoslynDebug.Assert((object)valueField != null);
yield return valueField;
}
foreach (var m in this.GetMembers())
{
switch (m.Kind)
{
case SymbolKind.Field:
if (m is TupleErrorFieldSymbol)
{
break;
}
yield return (FieldSymbol)m;
break;
case SymbolKind.Event:
FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField;
if ((object?)associatedField != null)
{
yield return associatedField;
}
break;
}
}
}
/// <summary>
/// During early attribute decoding, we consider a safe subset of all members that will not
/// cause cyclic dependencies. Get all such members for this symbol.
///
/// In particular, this method will return nested types and fields (other than auto-property
/// backing fields).
/// </summary>
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return GetEarlyAttributeDecodingMembersDictionary().Flatten();
}
/// <summary>
/// During early attribute decoding, we consider a safe subset of all members that will not
/// cause cyclic dependencies. Get all such members for this symbol that have a particular name.
///
/// In particular, this method will return nested types and fields (other than auto-property
/// backing fields).
/// </summary>
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
ImmutableArray<Symbol> result;
return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty;
}
private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary()
{
if (_lazyEarlyAttributeDecodingMembersDictionary == null)
{
if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result)
{
return result;
}
var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached
// NOTE: members were added in a single pass over the syntax, so they're already
// in lexical order.
Dictionary<string, ImmutableArray<Symbol>> membersByName;
if (!membersAndInitializers.HaveIndexers)
{
membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name);
}
else
{
// We can't include indexer symbol yet, because we don't know
// what name it will have after attribute binding (because of
// IndexerNameAttribute).
membersByName = membersAndInitializers.NonTypeMembers.
WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)).
ToDictionary(s => s.Name);
}
AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary());
Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null);
}
return _lazyEarlyAttributeDecodingMembersDictionary;
}
// NOTE: this method should do as little work as possible
// we often need to get members just to do a lookup.
// All additional checks and diagnostics may be not
// needed yet or at all.
protected MembersAndInitializers GetMembersAndInitializers()
{
var membersAndInitializers = _lazyMembersAndInitializers;
if (membersAndInitializers != null)
{
return membersAndInitializers;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
membersAndInitializers = BuildMembersAndInitializers(diagnostics);
var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null);
if (alreadyKnown != null)
{
diagnostics.Free();
return alreadyKnown;
}
AddDeclarationDiagnostics(diagnostics);
diagnostics.Free();
_lazyDeclaredMembersAndInitializers = null;
return membersAndInitializers!;
}
/// <summary>
/// The purpose of this function is to assert that the <paramref name="member"/> symbol
/// is actually among the symbols cached by this type symbol in a way that ensures
/// that any consumer of standard APIs to get to type's members is going to get the same
/// symbol (same instance) for the member rather than an equivalent, but different instance.
/// </summary>
[Conditional("DEBUG")]
internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false)
{
if (member is FieldSymbol && forDiagnostics && this.IsTupleType)
{
// There is a problem with binding types of fields in tuple types.
// Skipping verification for them temporarily.
return;
}
if (member is NamedTypeSymbol type)
{
RoslynDebug.AssertOrFailFast(forDiagnostics);
RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true);
return;
}
else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol)
{
RoslynDebug.AssertOrFailFast(forDiagnostics);
return;
}
else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e)
{
RoslynDebug.AssertOrFailFast(forDiagnostics);
// Backing fields for field-like events are not added to the members list.
member = e;
}
var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers);
if (isMemberInCompleteMemberList(membersAndInitializers, member))
{
return;
}
if (membersAndInitializers is null)
{
if (member is SynthesizedSimpleProgramEntryPointSymbol)
{
RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member));
return;
}
var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers);
RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel);
if (declared is object)
{
if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member)
{
return;
}
}
else
{
// It looks like there was a race and we need to check _lazyMembersAndInitializers again
membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers);
RoslynDebug.AssertOrFailFast(membersAndInitializers is object);
if (isMemberInCompleteMemberList(membersAndInitializers, member))
{
return;
}
}
}
RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure.");
static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member)
{
return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true;
}
}
protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName()
{
if (this.state.HasComplete(CompletionPart.Members))
{
return _lazyMembersDictionary!;
}
return GetMembersByNameSlow();
}
private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow()
{
if (_lazyMembersDictionary == null)
{
var diagnostics = BindingDiagnosticBag.GetInstance();
var membersDictionary = MakeAllMembers(diagnostics);
if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null)
{
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.Members);
}
diagnostics.Free();
}
state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken));
return _lazyMembersDictionary;
}
internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents()
{
var membersAndInitializers = this.GetMembersAndInitializers();
return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent);
}
protected void AfterMembersChecks(BindingDiagnosticBag diagnostics)
{
if (IsInterface)
{
CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics);
}
CheckMemberNamesDistinctFromType(diagnostics);
CheckMemberNameConflicts(diagnostics);
CheckRecordMemberNames(diagnostics);
CheckSpecialMemberErrors(diagnostics);
CheckTypeParameterNameConflicts(diagnostics);
CheckAccessorNameConflicts(diagnostics);
bool unused = KnownCircularStruct;
CheckSequentialOnPartialType(diagnostics);
CheckForProtectedInStaticClass(diagnostics);
CheckForUnmatchedOperators(diagnostics);
var location = Locations[0];
var compilation = DeclaringCompilation;
if (this.IsRefLikeType)
{
compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (this.IsReadOnly)
{
compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true);
}
var baseType = BaseTypeNoUseSiteDiagnostics;
var interfaces = GetInterfacesToEmit();
// https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations.
if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger()))
{
compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (compilation.ShouldEmitNullableAttributes(this))
{
if (ShouldEmitNullableContextValue(out _))
{
compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute()))
{
compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true);
}
}
if (interfaces.Any(t => needsTupleElementNamesAttribute(t)))
{
// Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding)
// so the checking of all interfaces here involves some redundancy.
Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics);
}
bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate)
{
return ((object)baseType != null && predicate(baseType)) ||
interfaces.Any(predicate);
}
static bool needsTupleElementNamesAttribute(TypeSymbol type)
{
if (type is null)
{
return false;
}
var resultType = type.VisitType(
predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(),
arg: (object?)null);
return resultType is object;
}
}
private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics)
{
foreach (var member in GetMembersAndInitializers().NonTypeMembers)
{
CheckMemberNameDistinctFromType(member, diagnostics);
}
}
private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics)
{
if (declaration.Kind != DeclarationKind.Record &&
declaration.Kind != DeclarationKind.RecordStruct)
{
return;
}
foreach (var member in GetMembers("Clone"))
{
diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]);
}
}
private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics)
{
Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName();
// Collisions involving indexers are handled specially.
CheckIndexerNameConflicts(diagnostics, membersByName);
// key and value will be the same object in these dictionaries.
var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer);
var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer);
var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer);
// SPEC: The signature of an operator must differ from the signatures of all other
// SPEC: operators declared in the same class.
// DELIBERATE SPEC VIOLATION:
// The specification does not state that a user-defined conversion reserves the names
// op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt
// to define a field or a conflicting method with the metadata name of a user-defined
// conversion is an error. We preserve this reasonable behavior.
//
// Similarly, we treat "public static C operator +(C, C)" as colliding with
// "public static C op_Addition(C, C)". Fortunately, this behavior simply
// falls out of treating user-defined operators as ordinary methods; we do
// not need any special handling in this method.
//
// However, we must have special handling for conversions because conversions
// use a completely different rule for detecting collisions between two
// conversions: conversion signatures consist only of the source and target
// types of the conversions, and not the kind of the conversion (implicit or explicit),
// the name of the method, and so on.
//
// Therefore we must detect the following kinds of member name conflicts:
//
// 1. a method, conversion or field has the same name as a (different) field (* see note below)
// 2. a method has the same method signature as another method or conversion
// 3. a conversion has the same conversion signature as another conversion.
//
// However, we must *not* detect "a conversion has the same *method* signature
// as another conversion" because conversions are allowed to overload on
// return type but methods are not.
//
// (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for
// "non-method, non-conversion, non-type member", rather than spelling out
// "field, property or event...")
foreach (var pair in membersByName)
{
var name = pair.Key;
Symbol? lastSym = GetTypeMembers(name).FirstOrDefault();
methodsBySignature.Clear();
// Conversion collisions do not consider the name of the conversion,
// so do not clear that dictionary.
foreach (var symbol in pair.Value)
{
if (symbol.Kind == SymbolKind.NamedType ||
symbol.IsAccessor() ||
symbol.IsIndexer())
{
continue;
}
// We detect the first category of conflict by running down the list of members
// of the same name, and producing an error when we discover any of the following
// "bad transitions".
//
// * a method or conversion that comes after any field (not necessarily directly)
// * a field directly following a field
// * a field directly following a method or conversion
//
// Furthermore: we do not wish to detect collisions between nested types in
// this code; that is tested elsewhere. However, we do wish to detect a collision
// between a nested type and a field, method or conversion. Therefore we
// initialize our "bad transition" detector with a type of the given name,
// if there is one. That way we also detect the transitions of "method following
// type", and so on.
//
// The "lastSym" local below is used to detect these transitions. Its value is
// one of the following:
//
// * a nested type of the given name, or
// * the first method of the given name, or
// * the most recently processed field of the given name.
//
// If either the current symbol or the "last symbol" are not methods then
// there must be a collision:
//
// * if the current symbol is not a method and the last symbol is, then
// there is a field directly following a method of the same name
// * if the current symbol is a method and the last symbol is not, then
// there is a method directly or indirectly following a field of the same name,
// or a method of the same name as a nested type.
// * if neither are methods then either we have a field directly
// following a field of the same name, or a field and a nested type of the same name.
//
if (lastSym is object)
{
if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method)
{
if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name);
}
}
if (lastSym.Kind == SymbolKind.Method)
{
lastSym = symbol;
}
}
}
else
{
lastSym = symbol;
}
// That takes care of the first category of conflict; we detect the
// second and third categories as follows:
var conversion = symbol as SourceUserDefinedConversionSymbol;
var method = symbol as SourceMemberMethodSymbol;
if (!(conversion is null))
{
// Does this conversion collide *as a conversion* with any previously-seen
// conversion?
if (!conversionsAsConversions.Add(conversion))
{
// CS0557: Duplicate user-defined conversion in type 'C'
diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this);
}
else
{
// The other set might already contain a conversion which would collide
// *as a method* with the current conversion.
if (!conversionsAsMethods.ContainsKey(conversion))
{
conversionsAsMethods.Add(conversion, conversion);
}
}
// Does this conversion collide *as a method* with any previously-seen
// non-conversion method?
if (methodsBySignature.TryGetValue(conversion, out var previousMethod))
{
ReportMethodSignatureCollision(diagnostics, conversion, previousMethod);
}
// Do not add the conversion to the set of previously-seen methods; that set
// is only non-conversion methods.
}
else if (!(method is null))
{
// Does this method collide *as a method* with any previously-seen
// conversion?
if (conversionsAsMethods.TryGetValue(method, out var previousConversion))
{
ReportMethodSignatureCollision(diagnostics, method, previousConversion);
}
// Do not add the method to the set of previously-seen conversions.
// Does this method collide *as a method* with any previously-seen
// non-conversion method?
if (methodsBySignature.TryGetValue(method, out var previousMethod))
{
ReportMethodSignatureCollision(diagnostics, method, previousMethod);
}
else
{
// We haven't seen this method before. Make a note of it in case
// we see a colliding method later.
methodsBySignature.Add(method, method);
}
}
}
}
}
// Report a name conflict; the error is reported on the location of method1.
// UNDONE: Consider adding a secondary location pointing to the second method.
private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2)
{
switch (method1, method2)
{
case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }):
case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }):
// these could be 2 parts of the same partial method.
// Partial methods are allowed to collide by signature.
return;
case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }):
return;
}
// If method1 is a constructor only because its return type is missing, then
// we've already produced a diagnostic for the missing return type and we suppress the
// diagnostic about duplicate signature.
if (method1.MethodKind == MethodKind.Constructor &&
((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name)
{
return;
}
Debug.Assert(method1.ParameterCount == method2.ParameterCount);
for (int i = 0; i < method1.ParameterCount; i++)
{
var refKind1 = method1.Parameters[i].RefKind;
var refKind2 = method2.Parameters[i].RefKind;
if (refKind1 != refKind2)
{
// '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}'
var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD;
diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString());
return;
}
}
// Special case: if there are two destructors, use the destructor syntax instead of "Finalize"
var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ?
"~" + this.Name :
(method1.IsConstructor() ? this.Name : method1.Name);
// Type '{1}' already defines a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this);
}
private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName)
{
PooledHashSet<string>? typeParameterNames = null;
if (this.Arity > 0)
{
typeParameterNames = PooledHashSet<string>.GetInstance();
foreach (TypeParameterSymbol typeParameter in this.TypeParameters)
{
typeParameterNames.Add(typeParameter.Name);
}
}
var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer);
// Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because
// they may be explicit interface implementations.
foreach (var members in membersByName.Values)
{
string? lastIndexerName = null;
indexersBySignature.Clear();
foreach (var symbol in members)
{
if (symbol.IsIndexer())
{
PropertySymbol indexer = (PropertySymbol)symbol;
CheckIndexerSignatureCollisions(
indexer,
diagnostics,
membersByName,
indexersBySignature,
ref lastIndexerName);
// Also check for collisions with type parameters, which aren't in the member map.
// NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts.
if (typeParameterNames != null)
{
string indexerName = indexer.MetadataName;
if (typeParameterNames.Contains(indexerName))
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName);
continue;
}
}
}
}
}
typeParameterNames?.Free();
}
private void CheckIndexerSignatureCollisions(
PropertySymbol indexer,
BindingDiagnosticBag diagnostics,
Dictionary<string, ImmutableArray<Symbol>> membersByName,
Dictionary<PropertySymbol, PropertySymbol> indexersBySignature,
ref string? lastIndexerName)
{
if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked
{
string indexerName = indexer.MetadataName;
if (lastIndexerName != null && lastIndexerName != indexerName)
{
// NOTE: dev10 checks indexer names by comparing each to the previous.
// For example, if indexers are declared with names A, B, A, B, then there
// will be three errors - one for each time the name is different from the
// previous one. If, on the other hand, the names are A, A, B, B, then
// there will only be one error because only one indexer has a different
// name from the previous one.
diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]);
}
lastIndexerName = indexerName;
if (Locations.Length == 1 || IsPartial)
{
if (membersByName.ContainsKey(indexerName))
{
// The name of the indexer is reserved - it can only be used by other indexers.
Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer));
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName);
}
}
}
if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature))
{
// Type '{1}' already defines a member called '{0}' with the same parameter types
// NOTE: Dev10 prints "this" as the name of the indexer.
diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this);
}
else
{
indexersBySignature[indexer] = indexer;
}
}
private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics)
{
var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary);
foreach (var member in this.GetMembersUnordered())
{
member.AfterAddingTypeMembersChecks(conversions, diagnostics);
}
}
private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics)
{
if (this.TypeKind == TypeKind.Delegate)
{
// Delegates do not have conflicts between their type parameter
// names and their methods; it is legal (though odd) to say
// delegate void D<Invoke>(Invoke x);
return;
}
if (Locations.Length == 1 || IsPartial)
{
foreach (var tp in TypeParameters)
{
foreach (var dup in GetMembers(tp.Name))
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name);
}
}
}
}
private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics)
{
// Report errors where property and event accessors
// conflict with other members of the same name.
foreach (Symbol symbol in this.GetMembersUnordered())
{
if (symbol.IsExplicitInterfaceImplementation())
{
// If there's a name conflict it will show up as a more specific
// interface implementation error.
continue;
}
switch (symbol.Kind)
{
case SymbolKind.Property:
{
var propertySymbol = (PropertySymbol)symbol;
this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics);
this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics);
break;
}
case SymbolKind.Event:
{
var eventSymbol = (EventSymbol)symbol;
this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics);
this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics);
break;
}
}
}
}
internal override bool KnownCircularStruct
{
get
{
if (_lazyKnownCircularStruct == (int)ThreeState.Unknown)
{
if (TypeKind != TypeKind.Struct)
{
Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown);
}
else
{
var diagnostics = BindingDiagnosticBag.GetInstance();
var value = (int)CheckStructCircularity(diagnostics).ToThreeState();
if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown)
{
AddDeclarationDiagnostics(diagnostics);
}
Debug.Assert(value == _lazyKnownCircularStruct);
diagnostics.Free();
}
}
return _lazyKnownCircularStruct == (int)ThreeState.True;
}
}
private bool CheckStructCircularity(BindingDiagnosticBag diagnostics)
{
Debug.Assert(TypeKind == TypeKind.Struct);
CheckFiniteFlatteningGraph(diagnostics);
return HasStructCircularity(diagnostics);
}
private bool HasStructCircularity(BindingDiagnosticBag diagnostics)
{
foreach (var valuesByName in GetMembersByName().Values)
{
foreach (var member in valuesByName)
{
if (member.Kind != SymbolKind.Field)
{
// NOTE: don't have to check field-like events, because they can't have struct types.
continue;
}
var field = (FieldSymbol)member;
if (field.IsStatic)
{
continue;
}
var type = field.NonPointerType();
if (((object)type != null) &&
(type.TypeKind == TypeKind.Struct) &&
BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) &&
!type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type
{
// If this is a backing field, report the error on the associated property.
var symbol = field.AssociatedSymbol ?? field;
if (symbol.Kind == SymbolKind.Parameter)
{
// We should stick to members for this error.
symbol = field;
}
// Struct member '{0}' of type '{1}' causes a cycle in the struct layout
diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type);
return true;
}
}
}
return false;
}
private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics)
{
if (!IsStatic)
{
return;
}
// no protected members allowed
foreach (var valuesByName in GetMembersByName().Values)
{
foreach (var member in valuesByName)
{
if (member is TypeSymbol)
{
// Duplicate Dev10's failure to diagnose this error.
continue;
}
if (member.DeclaredAccessibility.HasProtected())
{
if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor)
{
diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member);
}
}
}
}
}
private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics)
{
// SPEC: The true and false unary operators require pairwise declaration.
// SPEC: A compile-time error occurs if a class or struct declares one
// SPEC: of these operators without also declaring the other.
//
// SPEC DEFICIENCY: The line of the specification quoted above should say
// the same thing as the lines below: that the formal parameters of the
// paired true/false operators must match exactly. You can't do
// op true(S) and op false(S?) for example.
// SPEC: Certain binary operators require pairwise declaration. For every
// SPEC: declaration of either operator of a pair, there must be a matching
// SPEC: declaration of the other operator of the pair. Two operator
// SPEC: declarations match when they have the same return type and the same
// SPEC: type for each parameter. The following operators require pairwise
// SPEC: declaration: == and !=, > and <, >= and <=.
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName);
// We also produce a warning if == / != is overridden without also overriding
// Equals and GetHashCode, or if Equals is overridden without GetHashCode.
CheckForEqualityAndGetHashCode(diagnostics);
}
private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2)
{
var ops1 = this.GetOperators(operatorName1);
var ops2 = this.GetOperators(operatorName2);
CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2);
CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1);
}
private static void CheckForUnmatchedOperator(
BindingDiagnosticBag diagnostics,
ImmutableArray<MethodSymbol> ops1,
ImmutableArray<MethodSymbol> ops2,
string operatorName2)
{
foreach (var op1 in ops1)
{
bool foundMatch = false;
foreach (var op2 in ops2)
{
foundMatch = DoOperatorsPair(op1, op2);
if (foundMatch)
{
break;
}
}
if (!foundMatch)
{
// CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined
diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1,
SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2)));
}
}
}
private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2)
{
if (op1.ParameterCount != op2.ParameterCount)
{
return false;
}
for (int p = 0; p < op1.ParameterCount; ++p)
{
if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions))
{
return false;
}
}
if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
return true;
}
private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics)
{
if (this.IsInterfaceType())
{
// Interfaces are allowed to define Equals without GetHashCode if they want.
return;
}
if (IsRecord || IsRecordStruct)
{
// For records the warnings reported below are simply going to echo record specific errors,
// producing more noise.
return;
}
bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() ||
this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any();
bool overridesEquals = this.TypeOverridesObjectMethod("Equals");
if (hasOp || overridesEquals)
{
bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode");
if (overridesEquals && !overridesGHC)
{
// CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode()
diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this);
}
if (hasOp && !overridesEquals)
{
// CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o)
diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this);
}
if (hasOp && !overridesGHC)
{
// CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode()
diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this);
}
}
}
private bool TypeOverridesObjectMethod(string name)
{
foreach (var method in this.GetMembers(name).OfType<MethodSymbol>())
{
if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object)
{
return true;
}
}
return false;
}
private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics)
{
Debug.Assert(ReferenceEquals(this, this.OriginalDefinition));
if (AllTypeArgumentCount() == 0) return;
var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance);
instanceMap.Add(this, this);
foreach (var m in this.GetMembersUnordered())
{
var f = m as FieldSymbol;
if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue;
var type = (NamedTypeSymbol)f.Type;
if (InfiniteFlatteningGraph(this, type, instanceMap))
{
// Struct member '{0}' of type '{1}' causes a cycle in the struct layout
diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type);
//this.KnownCircularStruct = true;
return;
}
}
}
private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap)
{
if (!t.ContainsTypeParameter()) return false;
var tOriginal = t.OriginalDefinition;
if (instanceMap.TryGetValue(tOriginal, out var oldInstance))
{
// short circuit when we find a cycle, but only return true when the cycle contains the top struct
return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top);
}
else
{
instanceMap.Add(tOriginal, t);
try
{
foreach (var m in t.GetMembersUnordered())
{
var f = m as FieldSymbol;
if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue;
var type = (NamedTypeSymbol)f.Type;
if (InfiniteFlatteningGraph(top, type, instanceMap)) return true;
}
return false;
}
finally
{
instanceMap.Remove(tOriginal);
}
}
}
private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics)
{
if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential)
{
return;
}
SyntaxReference? whereFoundField = null;
if (this.SyntaxReferences.Length <= 1)
{
return;
}
foreach (var syntaxRef in this.SyntaxReferences)
{
var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax;
if (syntax == null)
{
continue;
}
foreach (var m in syntax.Members)
{
if (HasInstanceData(m))
{
if (whereFoundField != null && whereFoundField != syntaxRef)
{
diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this);
return;
}
whereFoundField = syntaxRef;
}
}
}
}
private static bool HasInstanceData(MemberDeclarationSyntax m)
{
switch (m.Kind())
{
case SyntaxKind.FieldDeclaration:
var fieldDecl = (FieldDeclarationSyntax)m;
return
!ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword);
case SyntaxKind.PropertyDeclaration:
// auto-property
var propertyDecl = (PropertyDeclarationSyntax)m;
return
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) &&
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) &&
propertyDecl.AccessorList != null &&
All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null);
case SyntaxKind.EventFieldDeclaration:
// field-like event declaration
var eventFieldDecl = (EventFieldDeclarationSyntax)m;
return
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) &&
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword);
default:
return false;
}
}
private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode
{
foreach (var t in list) { if (predicate(t)) return true; };
return false;
}
private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier)
{
foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; };
return false;
}
private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics)
{
Dictionary<string, ImmutableArray<Symbol>> membersByName;
var membersAndInitializers = GetMembersAndInitializers();
// Most types don't have indexers. If this is one of those types,
// just reuse the dictionary we build for early attribute decoding.
// For tuples, we also need to take the slow path.
if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object)
{
membersByName = _lazyEarlyAttributeDecodingMembersDictionary;
}
else
{
membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance);
// Merge types into the member dictionary
AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary());
}
MergePartialMembers(ref membersByName, diagnostics);
return membersByName;
}
private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName)
{
foreach (var pair in typesByName)
{
string name = pair.Key;
ImmutableArray<NamedTypeSymbol> types = pair.Value;
ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types);
ImmutableArray<Symbol> membersForName;
if (membersByName.TryGetValue(name, out membersForName))
{
membersByName[name] = membersForName.Concat(typesAsSymbols);
}
else
{
membersByName.Add(name, typesAsSymbols);
}
}
}
private sealed class DeclaredMembersAndInitializersBuilder
{
public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance();
public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance();
public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance();
public bool HaveIndexers;
public RecordDeclarationSyntax? RecordDeclarationWithParameters;
public SynthesizedRecordConstructor? RecordPrimaryConstructor;
public bool IsNullableEnabledForInstanceConstructorsAndFields;
public bool IsNullableEnabledForStaticConstructorsAndFields;
public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation)
{
return new DeclaredMembersAndInitializers(
NonTypeMembers.ToImmutableAndFree(),
MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers),
MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers),
HaveIndexers,
RecordDeclarationWithParameters,
RecordPrimaryConstructor,
isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields,
isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields,
compilation);
}
public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax)
{
ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic);
isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax);
}
public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value)
{
ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic);
isNullableEnabled = isNullableEnabled || value;
}
private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic)
{
return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields;
}
public void Free()
{
NonTypeMembers.Free();
foreach (var group in StaticInitializers)
{
group.Free();
}
StaticInitializers.Free();
foreach (var group in InstanceInitializers)
{
group.Free();
}
InstanceInitializers.Free();
}
internal void AddOrWrapTupleMembers(SourceMemberContainerTypeSymbol type)
{
this.NonTypeMembers = type.AddOrWrapTupleMembers(this.NonTypeMembers.ToImmutableAndFree());
}
}
protected sealed class DeclaredMembersAndInitializers
{
public readonly ImmutableArray<Symbol> NonTypeMembers;
public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers;
public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers;
public readonly bool HaveIndexers;
public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters;
public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor;
public readonly bool IsNullableEnabledForInstanceConstructorsAndFields;
public readonly bool IsNullableEnabledForStaticConstructorsAndFields;
public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers();
private DeclaredMembersAndInitializers()
{
}
public DeclaredMembersAndInitializers(
ImmutableArray<Symbol> nonTypeMembers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers,
bool haveIndexers,
RecordDeclarationSyntax? recordDeclarationWithParameters,
SynthesizedRecordConstructor? recordPrimaryConstructor,
bool isNullableEnabledForInstanceConstructorsAndFields,
bool isNullableEnabledForStaticConstructorsAndFields,
CSharpCompilation compilation)
{
Debug.Assert(!nonTypeMembers.IsDefault);
AssertInitializers(staticInitializers, compilation);
AssertInitializers(instanceInitializers, compilation);
Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol));
Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object);
this.NonTypeMembers = nonTypeMembers;
this.StaticInitializers = staticInitializers;
this.InstanceInitializers = instanceInitializers;
this.HaveIndexers = haveIndexers;
this.RecordDeclarationWithParameters = recordDeclarationWithParameters;
this.RecordPrimaryConstructor = recordPrimaryConstructor;
this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields;
this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields;
}
[Conditional("DEBUG")]
public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation)
{
Debug.Assert(!initializers.IsDefault);
if (initializers.IsEmpty)
{
return;
}
foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers)
{
Debug.Assert(!group.IsDefaultOrEmpty);
}
for (int i = 0; i < initializers.Length; i++)
{
if (i > 0)
{
Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0);
}
if (i + 1 < initializers.Length)
{
Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0);
}
if (initializers[i].Length != 1)
{
Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0);
}
}
}
}
private sealed class MembersAndInitializersBuilder
{
public ArrayBuilder<Symbol>? NonTypeMembers;
private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers;
private bool IsNullableEnabledForInstanceConstructorsAndFields;
private bool IsNullableEnabledForStaticConstructorsAndFields;
public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers)
{
Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel);
this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields;
this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields;
}
public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers)
{
var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers;
var instanceInitializers = InstanceInitializersForPositionalMembers is null
? declaredMembers.InstanceInitializers
: mergeInitializers();
return new MembersAndInitializers(
nonTypeMembers,
declaredMembers.StaticInitializers,
instanceInitializers,
declaredMembers.HaveIndexers,
isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields,
isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields);
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers()
{
Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0);
Debug.Assert(declaredMembers.RecordPrimaryConstructor is object);
Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object);
Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree);
Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start));
var groupCount = declaredMembers.InstanceInitializers.Length;
if (groupCount == 0)
{
return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree());
}
var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation;
var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation);
int insertAt;
for (insertAt = 0; insertAt < groupCount; insertAt++)
{
if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0)
{
break;
}
}
ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder;
if (insertAt != groupCount &&
declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree &&
declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start))
{
// Need to merge into the previous group
var declaredInitializers = declaredMembers.InstanceInitializers[insertAt];
var insertedInitializers = InstanceInitializersForPositionalMembers;
#if DEBUG
// initializers should be added in syntax order:
Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree);
Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start);
#endif
insertedInitializers.AddRange(declaredInitializers);
groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount);
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt);
groupsBuilder.Add(insertedInitializers.ToImmutableAndFree());
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1));
Debug.Assert(groupsBuilder.Count == groupCount);
}
else
{
Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree &&
declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start)));
groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1);
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt);
groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree());
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt);
Debug.Assert(groupsBuilder.Count == groupCount + 1);
}
var result = groupsBuilder.ToImmutableAndFree();
DeclaredMembersAndInitializers.AssertInitializers(result, compilation);
return result;
}
}
public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer)
{
if (InstanceInitializersForPositionalMembers is null)
{
InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance();
}
InstanceInitializersForPositionalMembers.Add(initializer);
}
public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers)
{
return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers;
}
public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers)
{
if (NonTypeMembers is null)
{
NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1);
NonTypeMembers.AddRange(declaredMembers.NonTypeMembers);
}
NonTypeMembers.Add(member);
}
public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax)
{
ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic);
isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax);
}
private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic)
{
return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields;
}
internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers)
{
if (initializers.Count == 0)
{
initializers.Free();
return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty;
}
var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count);
foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers)
{
builder.Add(group.ToImmutableAndFree());
}
initializers.Free();
return builder.ToImmutableAndFree();
}
public void Free()
{
NonTypeMembers?.Free();
InstanceInitializersForPositionalMembers?.Free();
}
}
private MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics)
{
var declaredMembersAndInitializers = getDeclaredMembersAndInitializers();
if (declaredMembersAndInitializers is null)
{
// Another thread completed the work before this one
return null;
}
var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers);
AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics);
if (Volatile.Read(ref _lazyMembersAndInitializers) != null)
{
// Another thread completed the work before this one
membersAndInitializersBuilder.Free();
return null;
}
return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers);
DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers()
{
var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers;
if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel)
{
return declaredMembersAndInitializers;
}
if (Volatile.Read(ref _lazyMembersAndInitializers) is not null)
{
// We're previously computed declared members and already cleared them out
// No need to compute them again
return null;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics);
var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel);
if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel)
{
diagnostics.Free();
return alreadyKnown;
}
AddDeclarationDiagnostics(diagnostics);
diagnostics.Free();
return declaredMembersAndInitializers!;
}
// Builds explicitly declared members (as opposed to synthesized members).
// This should not attempt to bind any method parameters as that would cause
// the members being built to be captured in the binder cache before the final
// list of members is determined.
DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics)
{
var builder = new DeclaredMembersAndInitializersBuilder();
AddDeclaredNontypeMembers(builder, diagnostics);
switch (TypeKind)
{
case TypeKind.Struct:
CheckForStructBadInitializers(builder, diagnostics);
CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics);
break;
case TypeKind.Enum:
CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics);
break;
case TypeKind.Class:
case TypeKind.Interface:
case TypeKind.Submission:
// No additional checking required.
break;
default:
break;
}
if (IsTupleType)
{
builder.AddOrWrapTupleMembers(this);
}
if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel)
{
// _lazyDeclaredMembersAndInitializers is already computed. no point to continue.
builder.Free();
return null;
}
return builder.ToReadOnlyAndFree(DeclaringCompilation);
}
}
internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints()
{
if (_lazySimpleProgramEntryPoints.IsDefault)
{
var diagnostics = BindingDiagnosticBag.GetInstance();
var simpleProgramEntryPoints = buildSimpleProgramEntryPoint(diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazySimpleProgramEntryPoints, simpleProgramEntryPoints))
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
Debug.Assert(!_lazySimpleProgramEntryPoints.IsDefault);
return _lazySimpleProgramEntryPoints;
ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics)
{
if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true }
|| this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName)
{
return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty;
}
ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null;
foreach (var singleDecl in declaration.Declarations)
{
if (singleDecl.IsSimpleProgram)
{
if (builder is null)
{
builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance();
}
else
{
Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation);
}
builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics));
}
}
if (builder is null)
{
return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty;
}
return builder.ToImmutableAndFree();
}
}
private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics)
{
if (TypeKind is TypeKind.Class)
{
AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers);
}
switch (TypeKind)
{
case TypeKind.Struct:
case TypeKind.Enum:
case TypeKind.Class:
case TypeKind.Interface:
case TypeKind.Submission:
AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics);
AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics);
break;
default:
break;
}
}
private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics)
{
foreach (var decl in this.declaration.Declarations)
{
if (!decl.HasAnyNontypeMembers)
{
continue;
}
if (_lazyMembersAndInitializers != null)
{
// membersAndInitializers is already computed. no point to continue.
return;
}
var syntax = decl.SyntaxReference.GetSyntax();
switch (syntax.Kind())
{
case SyntaxKind.EnumDeclaration:
AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics);
break;
case SyntaxKind.DelegateDeclaration:
SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics);
break;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
// The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit.
AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics);
break;
case SyntaxKind.CompilationUnit:
AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics);
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
var typeDecl = (TypeDeclarationSyntax)syntax;
AddNonTypeMembers(builder, typeDecl.Members, diagnostics);
break;
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
var recordDecl = (RecordDeclarationSyntax)syntax;
var parameterList = recordDecl.ParameterList;
noteRecordParameters(recordDecl, parameterList, builder, diagnostics);
AddNonTypeMembers(builder, recordDecl.Members, diagnostics);
break;
default:
throw ExceptionUtilities.UnexpectedValue(syntax.Kind());
}
}
void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics)
{
if (parameterList is null)
{
return;
}
if (builder.RecordDeclarationWithParameters is null)
{
builder.RecordDeclarationWithParameters = syntax;
var ctor = new SynthesizedRecordConstructor(this, syntax);
builder.RecordPrimaryConstructor = ctor;
var compilation = DeclaringCompilation;
builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList);
if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } })
{
builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList);
}
}
else
{
diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location);
}
}
}
internal Binder GetBinder(CSharpSyntaxNode syntaxNode)
{
return this.DeclaringCompilation.GetBinder(syntaxNode);
}
private void MergePartialMembers(
ref Dictionary<string, ImmutableArray<Symbol>> membersByName,
BindingDiagnosticBag diagnostics)
{
var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count);
memberNames.AddRange(membersByName.Keys);
//key and value will be the same object
var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer);
foreach (var name in memberNames)
{
methodsBySignature.Clear();
foreach (var symbol in membersByName[name])
{
var method = symbol as SourceMemberMethodSymbol;
if (method is null || !method.IsPartial)
{
continue; // only partial methods need to be merged
}
if (methodsBySignature.TryGetValue(method, out var prev))
{
var prevPart = (SourceOrdinaryMethodSymbol)prev;
var methodPart = (SourceOrdinaryMethodSymbol)method;
if (methodPart.IsPartialImplementation &&
(prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart)))
{
// A partial method may not have multiple implementing declarations
diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]);
}
else if (methodPart.IsPartialDefinition &&
(prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart)))
{
// A partial method may not have multiple defining declarations
diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]);
}
else
{
if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary)
{
// Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel.
membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName);
}
membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart);
}
}
else
{
methodsBySignature.Add(method, method);
}
}
foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values)
{
// partial implementations not paired with a definition
if (method.IsPartialImplementation && method.OtherPartOfPartial is null)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method);
}
else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true })
{
diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method);
}
}
}
memberNames.Free();
}
/// <summary>
/// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name),
/// and returning the combined symbol.
/// </summary>
/// <param name="symbols">The symbols array containing both the latent and implementing declaration</param>
/// <param name="part1">One of the two declarations</param>
/// <param name="part2">The other declaration</param>
/// <returns>An updated symbols array containing only one method symbol representing the two parts</returns>
private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2)
{
SourceOrdinaryMethodSymbol definition;
SourceOrdinaryMethodSymbol implementation;
if (part1.IsPartialDefinition)
{
definition = part1;
implementation = part2;
}
else
{
definition = part2;
implementation = part1;
}
SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation);
// a partial method is represented in the member list by its definition part:
return Remove(symbols, implementation);
}
private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol)
{
var builder = ArrayBuilder<Symbol>.GetInstance();
foreach (var s in symbols)
{
if (!ReferenceEquals(s, symbol))
{
builder.Add(s);
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Report an error if a member (other than a method) exists with the same name
/// as the property accessor, or if a method exists with the same name and signature.
/// </summary>
private void CheckForMemberConflictWithPropertyAccessor(
PropertySymbol propertySymbol,
bool getNotSet,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller
MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod;
string accessorName;
if ((object)accessor != null)
{
accessorName = accessor.Name;
}
else
{
string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name;
accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName,
getNotSet,
propertySymbol.IsCompilationOutputWinMdObj());
}
foreach (var symbol in GetMembers(accessorName))
{
if (symbol.Kind != SymbolKind.Method)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName);
return;
}
else
{
var methodSymbol = (MethodSymbol)symbol;
if ((methodSymbol.MethodKind == MethodKind.Ordinary) &&
ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters))
{
// Type '{1}' already reserves a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this);
return;
}
}
}
}
/// <summary>
/// Report an error if a member (other than a method) exists with the same name
/// as the event accessor, or if a method exists with the same name and signature.
/// </summary>
private void CheckForMemberConflictWithEventAccessor(
EventSymbol eventSymbol,
bool isAdder,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller
string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder);
foreach (var symbol in GetMembers(accessorName))
{
if (symbol.Kind != SymbolKind.Method)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName);
return;
}
else
{
var methodSymbol = (MethodSymbol)symbol;
if ((methodSymbol.MethodKind == MethodKind.Ordinary) &&
ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters))
{
// Type '{1}' already reserves a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this);
return;
}
}
}
}
/// <summary>
/// Return the location of the accessor, or if no accessor, the location of the property.
/// </summary>
private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet)
{
var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol;
return locationFrom.Locations[0];
}
/// <summary>
/// Return the location of the accessor, or if no accessor, the location of the event.
/// </summary>
private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder)
{
var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol;
return locationFrom.Locations[0];
}
/// <summary>
/// Return true if the method parameters match the parameters of the
/// property accessor, including the value parameter for the setter.
/// </summary>
private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams)
{
var propertyParams = propertySymbol.Parameters;
var numParams = propertyParams.Length + (getNotSet ? 0 : 1);
if (numParams != methodParams.Length)
{
return false;
}
for (int i = 0; i < numParams; i++)
{
var methodParam = methodParams[i];
if (methodParam.RefKind != RefKind.None)
{
return false;
}
var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type;
if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
}
return true;
}
/// <summary>
/// Return true if the method parameters match the parameters of the
/// event accessor, including the value parameter.
/// </summary>
private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams)
{
return
methodParams.Length == 1 &&
methodParams[0].RefKind == RefKind.None &&
eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions);
}
private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics)
{
// The previous enum constant used to calculate subsequent
// implicit enum constants. (This is the most recent explicit
// enum constant or the first implicit constant if no explicit values.)
SourceEnumConstantSymbol? otherSymbol = null;
// Offset from "otherSymbol".
int otherSymbolOffset = 0;
foreach (var member in syntax.Members)
{
SourceEnumConstantSymbol symbol;
var valueOpt = member.EqualsValue;
if (valueOpt != null)
{
symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics);
}
else
{
symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics);
}
result.NonTypeMembers.Add(symbol);
if (valueOpt != null || otherSymbol is null)
{
otherSymbol = symbol;
otherSymbolOffset = 1;
}
else
{
otherSymbolOffset++;
}
}
}
private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node)
{
if (initializers == null)
{
initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance();
}
else if (initializers.Count != 0)
{
// initializers should be added in syntax order:
Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree);
Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start);
}
initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node));
}
private static void AddInitializers(
ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers,
ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt)
{
if (siblingsOpt != null)
{
allInitializers.Add(siblingsOpt);
}
}
private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics)
{
foreach (var member in nonTypeMembers)
{
CheckInterfaceMember(member, diagnostics);
}
}
private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics)
{
switch (member.Kind)
{
case SymbolKind.Field:
break;
case SymbolKind.Method:
var meth = (MethodSymbol)member;
switch (meth.MethodKind)
{
case MethodKind.Constructor:
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]);
break;
case MethodKind.Conversion:
if (!meth.IsAbstract)
{
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]);
}
break;
case MethodKind.UserDefinedOperator:
if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName))
{
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]);
}
break;
case MethodKind.Destructor:
diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]);
break;
case MethodKind.ExplicitInterfaceImplementation:
//CS0541 is handled in SourcePropertySymbol
case MethodKind.Ordinary:
case MethodKind.LocalFunction:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.EventAdd:
case MethodKind.EventRemove:
case MethodKind.StaticConstructor:
break;
default:
throw ExceptionUtilities.UnexpectedValue(meth.MethodKind);
}
break;
case SymbolKind.Property:
break;
case SymbolKind.Event:
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
private static void CheckForStructDefaultConstructors(
ArrayBuilder<Symbol> members,
bool isEnum,
BindingDiagnosticBag diagnostics)
{
foreach (var s in members)
{
var m = s as MethodSymbol;
if (!(m is null))
{
if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0)
{
var location = m.Locations[0];
if (isEnum)
{
diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location);
}
else
{
MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location);
if (m.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location);
}
}
}
}
}
}
private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics)
{
Debug.Assert(TypeKind == TypeKind.Struct);
if (builder.RecordDeclarationWithParameters is not null)
{
Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record
&& record.Kind() == SyntaxKind.RecordStructDeclaration);
return;
}
foreach (var initializers in builder.InstanceInitializers)
{
foreach (FieldOrPropertyInitializer initializer in initializers)
{
var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt;
MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]);
}
}
}
private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers)
{
var simpleProgramEntryPoints = GetSimpleProgramEntryPoints();
foreach (var member in simpleProgramEntryPoints)
{
builder.AddNonTypeMember(member, declaredMembersAndInitializers);
}
}
private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics)
{
if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct))
{
return;
}
ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList;
var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate();
var fieldsByName = PooledDictionary<string, Symbol>.GetInstance();
var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers);
var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1);
var memberNames = PooledHashSet<string>.GetInstance();
foreach (var member in membersSoFar)
{
memberNames.Add(member.Name);
switch (member)
{
case EventSymbol:
case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }:
continue;
case FieldSymbol { Name: var fieldName }:
if (!fieldsByName.ContainsKey(fieldName))
{
fieldsByName.Add(fieldName, member);
}
continue;
}
if (!memberSignatures.ContainsKey(member))
{
memberSignatures.Add(member, member);
}
}
CSharpCompilation compilation = this.DeclaringCompilation;
bool isRecordClass = declaration.Kind == DeclarationKind.Record;
// Positional record
bool primaryAndCopyCtorAmbiguity = false;
if (!(paramList is null))
{
Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object);
// primary ctor
var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor;
Debug.Assert(ctor is object);
members.Add(ctor);
if (ctor.ParameterCount != 0)
{
// properties and Deconstruct
var existingOrAddedMembers = addProperties(ctor.Parameters);
addDeconstruct(ctor, existingOrAddedMembers);
}
if (isRecordClass)
{
primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions);
}
}
if (isRecordClass)
{
addCopyCtor(primaryAndCopyCtorAmbiguity);
addCloneMethod();
}
PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null;
var thisEquals = addThisEquals(equalityContract);
if (isRecordClass)
{
addBaseEquals();
}
addObjectEquals(thisEquals);
var getHashCode = addGetHashCode(equalityContract);
addEqualityOperators();
if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode)
{
diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name);
}
var printMembers = addPrintMembersMethod(membersSoFar);
addToStringMethod(printMembers);
memberSignatures.Free();
fieldsByName.Free();
memberNames.Free();
// Synthesizing non-readonly properties in struct would require changing readonly logic for PrintMembers method synthesis
Debug.Assert(isRecordClass || !members.Any(m => m is PropertySymbol { GetMethod.IsEffectivelyReadOnly: false }));
// We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all
// going to the record declaration
members.AddRange(membersSoFar);
builder.NonTypeMembers?.Free();
builder.NonTypeMembers = members;
return;
void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers)
{
Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol));
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.DeconstructMethodName,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations,
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.Out
)),
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod))
{
members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics));
}
else
{
var deconstruct = (MethodSymbol)existingDeconstructMethod;
if (deconstruct.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct);
}
if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType);
}
if (deconstruct.IsStatic)
{
diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct);
}
}
}
void addCopyCtor(bool primaryAndCopyCtorAmbiguity)
{
Debug.Assert(isRecordClass);
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.InstanceConstructorName,
this,
MethodKind.Constructor,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(this),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.None
)),
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor))
{
var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count);
members.Add(copyCtor);
if (primaryAndCopyCtorAmbiguity)
{
diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]);
}
}
else
{
var constructor = (MethodSymbol)existingConstructor;
if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected))
{
diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor);
}
}
}
void addCloneMethod()
{
Debug.Assert(isRecordClass);
members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics));
}
MethodSymbol addPrintMembersMethod(IEnumerable<Symbol> userDefinedMembers)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.PrintMembersMethodName,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.None)),
RefKind.None,
isInitOnly: false,
isStatic: false,
returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)),
refCustomModifiers: ImmutableArray<CustomModifier>.Empty,
explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty);
MethodSymbol printMembersMethod;
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod))
{
printMembersMethod = new SynthesizedRecordPrintMembers(this, userDefinedMembers, memberOffset: members.Count, diagnostics);
members.Add(printMembersMethod);
}
else
{
printMembersMethod = (MethodSymbol)existingPrintMembersMethod;
if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()))
{
if (printMembersMethod.DeclaredAccessibility != Accessibility.Private)
{
diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod);
}
}
else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected)
{
diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod);
}
if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions))
{
if (!printMembersMethod.ReturnType.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType);
}
}
else if (isRecordClass)
{
SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics);
}
reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics);
}
return printMembersMethod;
}
void addToStringMethod(MethodSymbol printMethod)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.ObjectToString,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
isInitOnly: false,
isStatic: false,
returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)),
refCustomModifiers: ImmutableArray<CustomModifier>.Empty,
explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty);
var baseToStringMethod = getBaseToStringMethod();
if (baseToStringMethod is { IsSealed: true })
{
if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord))
{
var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion;
var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion();
diagnostics.Add(
ErrorCode.ERR_InheritingFromRecordWithSealedToString,
this.Locations[0],
languageVersion.ToDisplayString(),
new CSharpRequiredLanguageVersion(requiredVersion));
}
}
else
{
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod))
{
var toStringMethod = new SynthesizedRecordToString(
this,
printMethod,
memberOffset: members.Count,
isReadOnly: printMethod.IsEffectivelyReadOnly,
diagnostics);
members.Add(toStringMethod);
}
else
{
var toStringMethod = (MethodSymbol)existingToStringMethod;
if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed)
{
MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability(
diagnostics,
this.DeclaringCompilation,
toStringMethod.Locations[0]);
}
}
}
MethodSymbol? getBaseToStringMethod()
{
var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString);
var currentBaseType = this.BaseTypeNoUseSiteDiagnostics;
while (currentBaseType is not null)
{
foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString))
{
if (member is not MethodSymbol method)
continue;
if (method.GetLeastOverriddenMethod(null) == objectToString)
return method;
}
currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics;
}
return null;
}
}
ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters)
{
var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length);
int addedCount = 0;
foreach (ParameterSymbol param in recordParameters)
{
bool isInherited = false;
var syntax = param.GetNonNullSyntaxNode();
var targetProperty = new SignatureOnlyPropertySymbol(param.Name,
this,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
param.TypeWithAnnotations,
ImmutableArray<CustomModifier>.Empty,
isStatic: false,
ImmutableArray<PropertySymbol>.Empty);
if (!memberSignatures.TryGetValue(targetProperty, out var existingMember)
&& !fieldsByName.TryGetValue(param.Name, out existingMember))
{
existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true);
isInherited = true;
}
// There should be an error if we picked a member that is hidden
// This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630
if (existingMember is null)
{
addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics));
}
else if (existingMember is FieldSymbol { IsStatic: false } field
&& field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions))
{
Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics);
if (!isInherited || checkMemberNotHidden(field, param))
{
existingOrAddedMembers.Add(field);
}
}
else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop
&& prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions))
{
// There already exists a member corresponding to the candidate synthesized property.
if (isInherited && prop.IsAbstract)
{
addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics));
}
else if (!isInherited || checkMemberNotHidden(prop, param))
{
// Deconstruct() is specified to simply assign from this property to the corresponding out parameter.
existingOrAddedMembers.Add(prop);
}
}
else
{
diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter,
param.Locations[0],
new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)),
param.TypeWithAnnotations,
param.Name);
}
void addProperty(SynthesizedRecordPropertySymbol property)
{
existingOrAddedMembers.Add(property);
members.Add(property);
Debug.Assert(property.GetMethod is object);
Debug.Assert(property.SetMethod is object);
members.Add(property.GetMethod);
members.Add(property.SetMethod);
members.Add(property.BackingField);
builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal]));
addedCount++;
}
}
return existingOrAddedMembers.ToImmutableAndFree();
bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param)
{
if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name))
{
diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol);
return false;
}
return true;
}
}
void addObjectEquals(MethodSymbol thisEquals)
{
members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics));
}
MethodSymbol addGetHashCode(PropertySymbol? equalityContract)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.ObjectGetHashCode,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
MethodSymbol getHashCode;
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod))
{
getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics);
members.Add(getHashCode);
}
else
{
getHashCode = (MethodSymbol)existingHashCodeMethod;
if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed)
{
diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode);
}
}
return getHashCode;
}
PropertySymbol addEqualityContract()
{
Debug.Assert(isRecordClass);
var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName,
this,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)),
ImmutableArray<CustomModifier>.Empty,
isStatic: false,
ImmutableArray<PropertySymbol>.Empty);
PropertySymbol equalityContract;
if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty))
{
equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics);
members.Add(equalityContract);
members.Add(equalityContract.GetMethod);
}
else
{
equalityContract = (PropertySymbol)existingEqualityContractProperty;
if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())
{
if (equalityContract.DeclaredAccessibility != Accessibility.Private)
{
diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract);
}
}
else if (equalityContract.DeclaredAccessibility != Accessibility.Protected)
{
diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract);
}
if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions))
{
if (!equalityContract.Type.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type);
}
}
else
{
SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics);
}
if (equalityContract.GetMethod is null)
{
diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract);
}
reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics);
}
return equalityContract;
}
MethodSymbol addThisEquals(PropertySymbol? equalityContract)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.ObjectEquals,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(this),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.None
)),
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
MethodSymbol thisEquals;
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod))
{
thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics);
members.Add(thisEquals);
}
else
{
thisEquals = (MethodSymbol)existingEqualsMethod;
if (thisEquals.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals);
}
if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType);
}
reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics);
}
return thisEquals;
}
void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics)
{
if (isRecordClass &&
!IsSealed &&
((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed))
{
diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol);
}
else if (symbol.IsStatic)
{
diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol);
}
}
void addBaseEquals()
{
Debug.Assert(isRecordClass);
if (!BaseTypeNoUseSiteDiagnostics.IsObjectType())
{
members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics));
}
}
void addEqualityOperators()
{
members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics));
members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics));
}
}
private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics)
{
//we're not calling the helpers on NamedTypeSymbol base, because those call
//GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow)
var hasInstanceConstructor = false;
var hasParameterlessInstanceConstructor = false;
var hasStaticConstructor = false;
// CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the
// dictionary construction process. For now, this is more encapsulated.
var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers);
foreach (var member in membersSoFar)
{
if (member.Kind == SymbolKind.Method)
{
var method = (MethodSymbol)member;
switch (method.MethodKind)
{
case MethodKind.Constructor:
// Ignore the record copy constructor
if (!IsRecord ||
!(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor))
{
hasInstanceConstructor = true;
hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0;
}
break;
case MethodKind.StaticConstructor:
hasStaticConstructor = true;
break;
}
}
//kick out early if we've seen everything we're looking for
if (hasInstanceConstructor && hasStaticConstructor)
{
break;
}
}
// NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor".
// We won't insert a parameterless constructor for a struct if there already is one.
// The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table.
if ((!hasParameterlessInstanceConstructor && this.IsStructType()) ||
(!hasInstanceConstructor && !this.IsStatic && !this.IsInterface))
{
builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ?
new SynthesizedSubmissionConstructor(this, diagnostics) :
new SynthesizedInstanceConstructor(this),
declaredMembersAndInitializers);
}
// constants don't count, since they do not exist as fields at runtime
// NOTE: even for decimal constants (which require field initializers),
// we do not create .cctor here since a static constructor implicitly created for a decimal
// should not appear in the list returned by public API like GetMembers().
if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers))
{
// Note: we don't have to put anything in the method - the binder will
// do that when processing field initializers.
builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers);
}
if (this.IsScriptClass)
{
var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics);
builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers);
var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics);
builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers);
}
static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst));
}
}
private void AddNonTypeMembers(
DeclaredMembersAndInitializersBuilder builder,
SyntaxList<MemberDeclarationSyntax> members,
BindingDiagnosticBag diagnostics)
{
if (members.Count == 0)
{
return;
}
var firstMember = members[0];
var bodyBinder = this.GetBinder(firstMember);
ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null;
ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null;
var compilation = DeclaringCompilation;
foreach (var m in members)
{
if (_lazyMembersAndInitializers != null)
{
// membersAndInitializers is already computed. no point to continue.
return;
}
bool reportMisplacedGlobalCode = !m.HasErrors;
switch (m.Kind())
{
case SyntaxKind.FieldDeclaration:
{
var fieldSyntax = (FieldDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier));
}
bool modifierErrors;
var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors);
foreach (var variable in fieldSyntax.Declaration.Variables)
{
var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0
? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics)
: new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics);
builder.NonTypeMembers.Add(fieldSymbol);
// All fields are included in the nullable context for constructors and initializers, even fields without
// initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker.
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable);
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this,
DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static),
fieldSymbol);
}
if (variable.Initializer != null)
{
if (fieldSymbol.IsStatic)
{
AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer);
}
else
{
AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer);
}
}
}
}
break;
case SyntaxKind.MethodDeclaration:
{
var methodSyntax = (MethodDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(methodSyntax.Identifier));
}
var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics);
builder.NonTypeMembers.Add(method);
}
break;
case SyntaxKind.ConstructorDeclaration:
{
var constructorSyntax = (ConstructorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(constructorSyntax.Identifier));
}
bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax);
var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics);
builder.NonTypeMembers.Add(constructor);
if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer)
{
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled);
}
}
break;
case SyntaxKind.DestructorDeclaration:
{
var destructorSyntax = (DestructorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(destructorSyntax.Identifier));
}
// CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the
// runtime won't consider it a finalizer and it will not be marked as a destructor
// when it is loaded from metadata. Perhaps we should just treat it as an Ordinary
// method in such cases?
var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics);
builder.NonTypeMembers.Add(destructor);
}
break;
case SyntaxKind.PropertyDeclaration:
{
var propertySyntax = (PropertyDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(propertySyntax.Identifier));
}
var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics);
builder.NonTypeMembers.Add(property);
AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod);
FieldSymbol backingField = property.BackingField;
// TODO: can we leave this out of the member list?
// From the 10/12/11 design notes:
// In addition, we will change autoproperties to behavior in
// a similar manner and make the autoproperty fields private.
if ((object)backingField != null)
{
builder.NonTypeMembers.Add(backingField);
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax);
var initializer = propertySyntax.Initializer;
if (initializer != null)
{
if (IsScriptClass)
{
// also gather expression-declared variables from the initializer
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers,
initializer,
this,
DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0),
backingField);
}
if (property.IsStatic)
{
AddInitializer(ref staticInitializers, backingField, initializer);
}
else
{
AddInitializer(ref instanceInitializers, backingField, initializer);
}
}
}
}
break;
case SyntaxKind.EventFieldDeclaration:
{
var eventFieldSyntax = (EventFieldDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(
ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier));
}
foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables)
{
SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics);
builder.NonTypeMembers.Add(@event);
FieldSymbol? associatedField = @event.AssociatedField;
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this,
DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0),
associatedField);
}
if ((object?)associatedField != null)
{
// NOTE: specifically don't add the associated field to the members list
// (regard it as an implementation detail).
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator);
if (declarator.Initializer != null)
{
if (associatedField.IsStatic)
{
AddInitializer(ref staticInitializers, associatedField, declarator.Initializer);
}
else
{
AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer);
}
}
}
Debug.Assert((object)@event.AddMethod != null);
Debug.Assert((object)@event.RemoveMethod != null);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod);
}
}
break;
case SyntaxKind.EventDeclaration:
{
var eventSyntax = (EventDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(eventSyntax.Identifier));
}
var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics);
builder.NonTypeMembers.Add(@event);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod);
Debug.Assert(@event.AssociatedField is null);
}
break;
case SyntaxKind.IndexerDeclaration:
{
var indexerSyntax = (IndexerDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(indexerSyntax.ThisKeyword));
}
var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics);
builder.HaveIndexers = true;
builder.NonTypeMembers.Add(indexer);
AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod);
}
break;
case SyntaxKind.ConversionOperatorDeclaration:
{
var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(conversionOperatorSyntax.OperatorKeyword));
}
var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol(
this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics);
builder.NonTypeMembers.Add(method);
}
break;
case SyntaxKind.OperatorDeclaration:
{
var operatorSyntax = (OperatorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(operatorSyntax.OperatorKeyword));
}
var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol(
this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics);
builder.NonTypeMembers.Add(method);
}
break;
case SyntaxKind.GlobalStatement:
{
var globalStatement = ((GlobalStatementSyntax)m).Statement;
if (IsScriptClass)
{
var innerStatement = globalStatement;
// drill into any LabeledStatements
while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
{
innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
}
switch (innerStatement.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
// We shouldn't reach this place, but field declarations preceded with a label end up here.
// This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now.
var decl = (LocalDeclarationStatementSyntax)innerStatement;
foreach (var vdecl in decl.Declaration.Variables)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private,
containingFieldOpt: null);
}
break;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.LockStatement:
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers,
innerStatement,
this,
DeclarationModifiers.Private,
containingFieldOpt: null);
break;
default:
// no other statement introduces variables into the enclosing scope
break;
}
AddInitializer(ref instanceInitializers, null, globalStatement);
}
else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m))
{
diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement));
}
}
break;
default:
Debug.Assert(
SyntaxFacts.IsTypeDeclaration(m.Kind()) ||
m.Kind() is SyntaxKind.NamespaceDeclaration or
SyntaxKind.FileScopedNamespaceDeclaration or
SyntaxKind.IncompleteMember);
break;
}
}
AddInitializers(builder.InstanceInitializers, instanceInitializers);
AddInitializers(builder.StaticInitializers, staticInitializers);
}
private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt)
{
if (!(accessorOpt is null))
{
symbols.Add(accessorOpt);
}
}
internal override byte? GetLocalNullableContextValue()
{
byte? value;
if (!_flags.TryGetNullableContext(out value))
{
value = ComputeNullableContextValue();
_flags.SetNullableContext(value);
}
return value;
}
private byte? ComputeNullableContextValue()
{
var compilation = DeclaringCompilation;
if (!compilation.ShouldEmitNullableAttributes(this))
{
return null;
}
var builder = new MostCommonNullableValueBuilder();
var baseType = BaseTypeNoUseSiteDiagnostics;
if (baseType is object)
{
builder.AddValue(TypeWithAnnotations.Create(baseType));
}
foreach (var @interface in GetInterfacesToEmit())
{
builder.AddValue(TypeWithAnnotations.Create(@interface));
}
foreach (var typeParameter in TypeParameters)
{
typeParameter.GetCommonNullableValues(compilation, ref builder);
}
foreach (var member in GetMembersUnordered())
{
member.GetCommonNullableValues(compilation, ref builder);
}
// Not including lambdas or local functions.
return builder.MostCommonValue;
}
/// <summary>
/// Returns true if the overall nullable context is enabled for constructors and initializers.
/// </summary>
/// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param>
internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic)
{
var membersAndInitializers = GetMembersAndInitializers();
return useStatic ?
membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields :
membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields;
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
var compilation = DeclaringCompilation;
NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics;
if (baseType is object)
{
if (baseType.ContainsDynamic())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0));
}
if (baseType.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType));
}
if (baseType.ContainsTupleNames())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType));
}
}
if (compilation.ShouldEmitNullableAttributes(this))
{
if (ShouldEmitNullableContextValue(out byte nullableContextValue))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue));
}
if (baseType is object)
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType)));
}
}
}
#endregion
#region Extension Methods
internal bool ContainsExtensionMethods
{
get
{
if (!_lazyContainsExtensionMethods.HasValue())
{
bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods;
_lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState();
}
return _lazyContainsExtensionMethods.Value();
}
}
internal bool AnyMemberHasAttributes
{
get
{
if (!_lazyAnyMemberHasAttributes.HasValue())
{
bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes;
_lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState();
}
return _lazyAnyMemberHasAttributes.Value();
}
}
public override bool MightContainExtensionMethods
{
get
{
return this.ContainsExtensionMethods;
}
}
#endregion
public sealed override NamedTypeSymbol ConstructedFrom
{
get { return this; }
}
internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0;
internal class SynthesizedExplicitImplementations
{
public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty,
ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty);
public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods;
public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls;
private SynthesizedExplicitImplementations(
ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods,
ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls)
{
ForwardingMethods = forwardingMethods.NullToEmpty();
MethodImpls = methodImpls.NullToEmpty();
}
internal static SynthesizedExplicitImplementations Create(
ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods,
ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls)
{
if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty)
{
return Empty;
}
return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a named type symbol whose members are declared in source.
/// </summary>
internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol
{
// The flags type is used to compact many different bits of information efficiently.
private struct Flags
{
// We current pack everything into one 32-bit int; layout is given below.
//
// | |vvv|zzzz|f|d|yy|wwwwww|
//
// w = special type. 6 bits.
// y = IsManagedType. 2 bits.
// d = FieldDefinitionsNoted. 1 bit
// f = FlattenedMembersIsSorted. 1 bit.
// z = TypeKind. 4 bits.
// v = NullableContext. 3 bits.
private int _flags;
private const int SpecialTypeOffset = 0;
private const int SpecialTypeSize = 6;
private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize;
private const int ManagedKindSize = 2;
private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize;
private const int FieldDefinitionsNotedSize = 1;
private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize;
private const int FlattenedMembersIsSortedSize = 1;
private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize;
private const int TypeKindSize = 4;
private const int NullableContextOffset = TypeKindOffset + TypeKindSize;
private const int NullableContextSize = 3;
private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1;
private const int ManagedKindMask = (1 << ManagedKindSize) - 1;
private const int TypeKindMask = (1 << TypeKindSize) - 1;
private const int NullableContextMask = (1 << NullableContextSize) - 1;
private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset;
private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset;
public SpecialType SpecialType
{
get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); }
}
public ManagedKind ManagedKind
{
get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); }
}
public bool FieldDefinitionsNoted
{
get { return (_flags & FieldDefinitionsNotedBit) != 0; }
}
// True if "lazyMembersFlattened" is sorted.
public bool FlattenedMembersIsSorted
{
get { return (_flags & FlattenedMembersIsSortedBit) != 0; }
}
public TypeKind TypeKind
{
get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); }
}
#if DEBUG
static Flags()
{
// Verify masks are sufficient for values.
Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask));
Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask));
}
#endif
public Flags(SpecialType specialType, TypeKind typeKind)
{
int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset;
int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset;
_flags = specialTypeInt | typeKindInt;
}
public void SetFieldDefinitionsNoted()
{
ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit);
}
public void SetFlattenedMembersIsSorted()
{
ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit));
}
private static bool BitsAreUnsetOrSame(int bits, int mask)
{
return (bits & mask) == 0 || (bits & mask) == mask;
}
public void SetManagedKind(ManagedKind managedKind)
{
int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset;
Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet));
ThreadSafeFlagOperations.Set(ref _flags, bitsToSet);
}
public bool TryGetNullableContext(out byte? value)
{
return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value);
}
public bool SetNullableContext(byte? value)
{
return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset));
}
}
private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary =
PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer);
protected SymbolCompletionState state;
private Flags _flags;
private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics;
private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies;
private readonly DeclarationModifiers _declModifiers;
private readonly NamespaceOrTypeSymbol _containingSymbol;
protected readonly MergedTypeDeclaration declaration;
// The entry point symbol (resulting from top-level statements) is needed to construct non-type members because
// it contributes to their binders, so we have to compute it first.
// The value changes from "default" to "real value". The transition from "default" can only happen once.
private ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> _lazySimpleProgramEntryPoints;
// To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set)
// The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once.
private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel;
private MembersAndInitializers? _lazyMembersAndInitializers;
private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary;
private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary;
private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance);
private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers;
private ImmutableArray<Symbol> _lazyMembersFlattened;
private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations;
private int _lazyKnownCircularStruct;
private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized;
private ThreeState _lazyContainsExtensionMethods;
private ThreeState _lazyAnyMemberHasAttributes;
#region Construction
internal SourceMemberContainerTypeSymbol(
NamespaceOrTypeSymbol containingSymbol,
MergedTypeDeclaration declaration,
BindingDiagnosticBag diagnostics,
TupleExtraData? tupleData = null)
: base(tupleData)
{
// If we're dealing with a simple program, then we must be in the global namespace
Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram));
_containingSymbol = containingSymbol;
this.declaration = declaration;
TypeKind typeKind = declaration.Kind.ToTypeKind();
var modifiers = MakeModifiers(typeKind, diagnostics);
foreach (var singleDeclaration in declaration.Declarations)
{
diagnostics.AddRange(singleDeclaration.Diagnostics);
}
int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask);
if ((access & (access - 1)) != 0)
{ // more than one access modifier
if ((modifiers & DeclarationModifiers.Partial) != 0)
diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this);
access = access & ~(access - 1); // narrow down to one access modifier
modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all
modifiers |= (DeclarationModifiers)access; // except the one
}
_declModifiers = modifiers;
var specialType = access == (int)DeclarationModifiers.Public
? MakeSpecialType()
: SpecialType.None;
_flags = new Flags(specialType, typeKind);
var containingType = this.ContainingType;
if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected())
{
diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this);
}
state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately
}
private SpecialType MakeSpecialType()
{
// check if this is one of the COR library types
if (ContainingSymbol.Kind == SymbolKind.Namespace &&
ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes)
{
//for a namespace, the emitted name is a dot-separated list of containing namespaces
var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat);
emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName);
return SpecialTypes.GetTypeFromMetadataName(emittedName);
}
else
{
return SpecialType.None;
}
}
private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics)
{
Symbol containingSymbol = this.ContainingSymbol;
DeclarationModifiers defaultAccess;
var allowedModifiers = DeclarationModifiers.AccessibilityMask;
if (containingSymbol.Kind == SymbolKind.Namespace)
{
defaultAccess = DeclarationModifiers.Internal;
}
else
{
allowedModifiers |= DeclarationModifiers.New;
if (((NamedTypeSymbol)containingSymbol).IsInterface)
{
defaultAccess = DeclarationModifiers.Public;
}
else
{
defaultAccess = DeclarationModifiers.Private;
}
}
switch (typeKind)
{
case TypeKind.Class:
case TypeKind.Submission:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract
| DeclarationModifiers.Unsafe;
if (!this.IsRecord)
{
allowedModifiers |= DeclarationModifiers.Static;
}
break;
case TypeKind.Struct:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe;
if (!this.IsRecordStruct)
{
allowedModifiers |= DeclarationModifiers.Ref;
}
break;
case TypeKind.Interface:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe;
break;
case TypeKind.Delegate:
allowedModifiers |= DeclarationModifiers.Unsafe;
break;
}
bool modifierErrors;
var mods = MakeAndCheckTypeModifiers(
defaultAccess,
allowedModifiers,
diagnostics,
out modifierErrors);
this.CheckUnsafeModifier(mods, diagnostics);
if (!modifierErrors &&
(mods & DeclarationModifiers.Abstract) != 0 &&
(mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0)
{
diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this);
}
if (!modifierErrors &&
(mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static))
{
diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this);
}
switch (typeKind)
{
case TypeKind.Interface:
mods |= DeclarationModifiers.Abstract;
break;
case TypeKind.Struct:
case TypeKind.Enum:
mods |= DeclarationModifiers.Sealed;
break;
case TypeKind.Delegate:
mods |= DeclarationModifiers.Sealed;
break;
}
return mods;
}
private DeclarationModifiers MakeAndCheckTypeModifiers(
DeclarationModifiers defaultAccess,
DeclarationModifiers allowedModifiers,
BindingDiagnosticBag diagnostics,
out bool modifierErrors)
{
modifierErrors = false;
var result = DeclarationModifiers.Unset;
var partCount = declaration.Declarations.Length;
var missingPartial = false;
for (var i = 0; i < partCount; i++)
{
var decl = declaration.Declarations[i];
var mods = decl.Modifiers;
if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0)
{
missingPartial = true;
}
if (!modifierErrors)
{
mods = ModifierUtils.CheckModifiers(
mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics,
modifierTokens: null, modifierErrors: out modifierErrors);
// It is an error for the same modifier to appear multiple times.
if (!modifierErrors)
{
var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false);
if (info != null)
{
diagnostics.Add(info, this.Locations[0]);
modifierErrors = true;
}
}
}
if (result == DeclarationModifiers.Unset)
{
result = mods;
}
else
{
result |= mods;
}
}
if ((result & DeclarationModifiers.AccessibilityMask) == 0)
{
result |= defaultAccess;
}
if (missingPartial)
{
if ((result & DeclarationModifiers.Partial) == 0)
{
// duplicate definitions
switch (this.ContainingSymbol.Kind)
{
case SymbolKind.Namespace:
for (var i = 1; i < partCount; i++)
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol);
modifierErrors = true;
}
break;
case SymbolKind.NamedType:
for (var i = 1; i < partCount; i++)
{
if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial())
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name);
modifierErrors = true;
}
break;
}
}
else
{
for (var i = 0; i < partCount; i++)
{
var singleDeclaration = declaration.Declarations[i];
var mods = singleDeclaration.Modifiers;
if ((mods & DeclarationModifiers.Partial) == 0)
{
diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name);
modifierErrors = true;
}
}
}
}
if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword))
{
foreach (var syntaxRef in SyntaxReferences)
{
SyntaxToken? identifier = syntaxRef.GetSyntax() switch
{
BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier,
DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier,
_ => null
};
ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None);
}
}
return result;
}
internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location)
{
if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) &&
compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion())
{
diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name);
}
}
#endregion
#region Completion
internal sealed override bool RequiresCompletion
{
get { return true; }
}
internal sealed override bool HasComplete(CompletionPart part)
{
return state.HasComplete(part);
}
protected abstract void CheckBase(BindingDiagnosticBag diagnostics);
protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics);
internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken)
{
while (true)
{
// NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers.
cancellationToken.ThrowIfCancellationRequested();
var incompletePart = state.NextIncompletePart;
switch (incompletePart)
{
case CompletionPart.Attributes:
GetAttributes();
break;
case CompletionPart.StartBaseType:
case CompletionPart.FinishBaseType:
if (state.NotePartComplete(CompletionPart.StartBaseType))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
CheckBase(diagnostics);
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.FinishBaseType);
diagnostics.Free();
}
break;
case CompletionPart.StartInterfaces:
case CompletionPart.FinishInterfaces:
if (state.NotePartComplete(CompletionPart.StartInterfaces))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
CheckInterfaces(diagnostics);
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.FinishInterfaces);
diagnostics.Free();
}
break;
case CompletionPart.EnumUnderlyingType:
var discarded = this.EnumUnderlyingType;
break;
case CompletionPart.TypeArguments:
{
var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments
}
break;
case CompletionPart.TypeParameters:
// force type parameters
foreach (var typeParameter in this.TypeParameters)
{
typeParameter.ForceComplete(locationOpt, cancellationToken);
}
state.NotePartComplete(CompletionPart.TypeParameters);
break;
case CompletionPart.Members:
this.GetMembersByName();
break;
case CompletionPart.TypeMembers:
this.GetTypeMembersUnordered();
break;
case CompletionPart.SynthesizedExplicitImplementations:
this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked
break;
case CompletionPart.StartMemberChecks:
case CompletionPart.FinishMemberChecks:
if (state.NotePartComplete(CompletionPart.StartMemberChecks))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
AfterMembersChecks(diagnostics);
AddDeclarationDiagnostics(diagnostics);
// We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members
DeclaringCompilation.SymbolDeclaredEvent(this);
var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks);
Debug.Assert(thisThreadCompleted);
diagnostics.Free();
}
break;
case CompletionPart.MembersCompleted:
{
ImmutableArray<Symbol> members = this.GetMembersUnordered();
bool allCompleted = true;
if (locationOpt == null)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
member.ForceComplete(locationOpt, cancellationToken);
}
}
else
{
foreach (var member in members)
{
ForceCompleteMemberByLocation(locationOpt, member, cancellationToken);
allCompleted = allCompleted && member.HasComplete(CompletionPart.All);
}
}
if (!allCompleted)
{
// We did not complete all members so we won't have enough information for
// the PointedAtManagedTypeChecks, so just kick out now.
var allParts = CompletionPart.NamedTypeSymbolWithLocationAll;
state.SpinWaitComplete(allParts, cancellationToken);
return;
}
EnsureFieldDefinitionsNoted();
// We've completed all members, so we're ready for the PointedAtManagedTypeChecks;
// proceed to the next iteration.
state.NotePartComplete(CompletionPart.MembersCompleted);
break;
}
case CompletionPart.None:
return;
default:
// This assert will trigger if we forgot to handle any of the completion parts
Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0);
// any other values are completion parts intended for other kinds of symbols
state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll);
break;
}
state.SpinWaitComplete(incompletePart, cancellationToken);
}
throw ExceptionUtilities.Unreachable;
}
internal void EnsureFieldDefinitionsNoted()
{
if (_flags.FieldDefinitionsNoted)
{
return;
}
NoteFieldDefinitions();
}
private void NoteFieldDefinitions()
{
// we must note all fields once therefore we need to lock
var membersAndInitializers = this.GetMembersAndInitializers();
lock (membersAndInitializers)
{
if (!_flags.FieldDefinitionsNoted)
{
var assembly = (SourceAssemblySymbol)ContainingAssembly;
Accessibility containerEffectiveAccessibility = EffectiveAccessibility();
foreach (var member in membersAndInitializers.NonTypeMembers)
{
FieldSymbol field;
if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer)
{
continue;
}
Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility;
if (fieldDeclaredAccessibility == Accessibility.Private)
{
// mark private fields as tentatively unassigned and unread unless we discover otherwise.
assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true);
}
else if (containerEffectiveAccessibility == Accessibility.Private)
{
// mark effectively private fields as tentatively unassigned unless we discover otherwise.
assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false);
}
else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal)
{
// mark effectively internal fields as tentatively unassigned unless we discover otherwise.
// NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly.
// See property SourceAssemblySymbol.UnusedFieldWarnings.
assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false);
}
}
_flags.SetFieldDefinitionsNoted();
}
}
}
#endregion
#region Containers
public sealed override NamedTypeSymbol? ContainingType
{
get
{
return _containingSymbol as NamedTypeSymbol;
}
}
public sealed override Symbol ContainingSymbol
{
get
{
return _containingSymbol;
}
}
#endregion
#region Flags Encoded Properties
public override SpecialType SpecialType
{
get
{
return _flags.SpecialType;
}
}
public override TypeKind TypeKind
{
get
{
return _flags.TypeKind;
}
}
internal MergedTypeDeclaration MergedDeclaration
{
get
{
return this.declaration;
}
}
internal sealed override bool IsInterface
{
get
{
// TypeKind is computed eagerly, so this is cheap.
return this.TypeKind == TypeKind.Interface;
}
}
internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var managedKind = _flags.ManagedKind;
if (managedKind == ManagedKind.Unknown)
{
var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly);
managedKind = base.GetManagedKind(ref managedKindUseSiteInfo);
ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty);
ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty);
_flags.SetManagedKind(managedKind);
}
if (useSiteInfo.AccumulatesDiagnostics)
{
ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics;
// Ensure we have the latest value from the field
useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics);
Debug.Assert(!useSiteDiagnostics.IsDefault);
useSiteInfo.AddDiagnostics(useSiteDiagnostics);
}
if (useSiteInfo.AccumulatesDependencies)
{
ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies;
// Ensure we have the latest value from the field
useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies);
Debug.Assert(!useSiteDependencies.IsDefault);
useSiteInfo.AddDependencies(useSiteDependencies);
}
return managedKind;
}
public override bool IsStatic => HasFlag(DeclarationModifiers.Static);
public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref);
public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly);
public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed);
public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract);
internal bool IsPartial => HasFlag(DeclarationModifiers.Partial);
internal bool IsNew => HasFlag(DeclarationModifiers.New);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0;
public override Accessibility DeclaredAccessibility
{
get
{
return ModifierUtils.EffectiveAccessibility(_declModifiers);
}
}
/// <summary>
/// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields.
/// </summary>
private Accessibility EffectiveAccessibility()
{
var result = DeclaredAccessibility;
if (result == Accessibility.Private) return Accessibility.Private;
for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType)
{
switch (container.DeclaredAccessibility)
{
case Accessibility.Private:
return Accessibility.Private;
case Accessibility.Internal:
result = Accessibility.Internal;
continue;
}
}
return result;
}
#endregion
#region Syntax
public override bool IsScriptClass
{
get
{
var kind = this.declaration.Declarations[0].Kind;
return kind == DeclarationKind.Script || kind == DeclarationKind.Submission;
}
}
public override bool IsImplicitClass
{
get
{
return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass;
}
}
internal override bool IsRecord
{
get
{
return this.declaration.Declarations[0].Kind == DeclarationKind.Record;
}
}
internal override bool IsRecordStruct
{
get
{
return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct;
}
}
public override bool IsImplicitlyDeclared
{
get
{
return IsImplicitClass || IsScriptClass;
}
}
public override int Arity
{
get
{
return declaration.Arity;
}
}
public override string Name
{
get
{
return declaration.Name;
}
}
internal override bool MangleName
{
get
{
return Arity > 0;
}
}
internal override LexicalSortKey GetLexicalSortKey()
{
if (!_lazyLexicalSortKey.IsInitialized)
{
_lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation));
}
return _lazyLexicalSortKey;
}
public override ImmutableArray<Location> Locations
{
get
{
return declaration.NameLocations.Cast<SourceLocation, Location>();
}
}
public ImmutableArray<SyntaxReference> SyntaxReferences
{
get
{
return this.declaration.SyntaxReferences;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return SyntaxReferences;
}
}
// This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences
internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken)
{
var declarations = declaration.Declarations;
if (IsImplicitlyDeclared && declarations.IsEmpty)
{
return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken);
}
foreach (var declaration in declarations)
{
cancellationToken.ThrowIfCancellationRequested();
var syntaxRef = declaration.SyntaxReference;
if (syntaxRef.SyntaxTree == tree &&
(!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value)))
{
return true;
}
}
return false;
}
#endregion
#region Members
/// <summary>
/// Encapsulates information about the non-type members of a (i.e. this) type.
/// 1) For non-initializers, symbols are created and stored in a list.
/// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are
/// stored with other initialized fields and properties from the same syntax tree with
/// the same static-ness.
/// </summary>
protected sealed class MembersAndInitializers
{
internal readonly ImmutableArray<Symbol> NonTypeMembers;
internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers;
internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers;
internal readonly bool HaveIndexers;
internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields;
internal readonly bool IsNullableEnabledForStaticConstructorsAndFields;
public MembersAndInitializers(
ImmutableArray<Symbol> nonTypeMembers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers,
bool haveIndexers,
bool isNullableEnabledForInstanceConstructorsAndFields,
bool isNullableEnabledForStaticConstructorsAndFields)
{
Debug.Assert(!nonTypeMembers.IsDefault);
Debug.Assert(!staticInitializers.IsDefault);
Debug.Assert(staticInitializers.All(g => !g.IsDefault));
Debug.Assert(!instanceInitializers.IsDefault);
Debug.Assert(instanceInitializers.All(g => !g.IsDefault));
Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol));
Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer()));
this.NonTypeMembers = nonTypeMembers;
this.StaticInitializers = staticInitializers;
this.InstanceInitializers = instanceInitializers;
this.HaveIndexers = haveIndexers;
this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields;
this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields;
}
}
internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers
{
get { return GetMembersAndInitializers().StaticInitializers; }
}
internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers
{
get { return GetMembersAndInitializers().InstanceInitializers; }
}
internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic)
{
if (IsScriptClass && !isStatic)
{
int aggregateLength = 0;
foreach (var declaration in this.declaration.Declarations)
{
var syntaxRef = declaration.SyntaxReference;
if (tree == syntaxRef.SyntaxTree)
{
return aggregateLength + position;
}
aggregateLength += syntaxRef.Span.Length;
}
throw ExceptionUtilities.Unreachable;
}
int syntaxOffset;
if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset))
{
return syntaxOffset;
}
if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start)
{
// With dynamic analysis instrumentation, the introducing declaration of a type can provide
// the syntax associated with both the analysis payload local of a synthesized constructor
// and with the constructor itself. If the synthesized constructor includes an initializer with a lambda,
// that lambda needs a closure that captures the analysis payload of the constructor,
// and the offset of the syntax for the local within the constructor is by definition zero.
return 0;
}
// an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one).
/// </summary>
internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset)
{
Debug.Assert(ctorInitializerLength >= 0);
var membersAndInitializers = GetMembersAndInitializers();
var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers;
if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength))
{
syntaxOffset = 0;
return false;
}
// |<-----------distanceFromCtorBody----------->|
// [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body]
// |<--preceding init len-->| ^
// position
int initializersLength = getInitializersLength(allInitializers);
int distanceFromInitializerStart = position - initializer.Syntax.Span.Start;
int distanceFromCtorBody =
initializersLength + ctorInitializerLength -
(precedingLength + distanceFromInitializerStart);
Debug.Assert(distanceFromCtorBody > 0);
// syntax offset 0 is at the start of the ctor body:
syntaxOffset = -distanceFromCtorBody;
return true;
static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree,
out FieldOrPropertyInitializer found, out int precedingLength)
{
precedingLength = 0;
foreach (var group in initializers)
{
if (!group.IsEmpty &&
group[0].Syntax.SyntaxTree == tree &&
position < group.Last().Syntax.Span.End)
{
// Found group of interest
var initializerIndex = IndexOfInitializerContainingPosition(group, position);
if (initializerIndex < 0)
{
break;
}
precedingLength += getPrecedingInitializersLength(group, initializerIndex);
found = group[initializerIndex];
return true;
}
precedingLength += getGroupLength(group);
}
found = default;
return false;
}
static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers)
{
int length = 0;
foreach (var initializer in initializers)
{
length += getInitializerLength(initializer);
}
return length;
}
static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index)
{
int length = 0;
for (var i = 0; i < index; i++)
{
length += getInitializerLength(initializers[i]);
}
return length;
}
static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
int length = 0;
foreach (var group in initializers)
{
length += getGroupLength(group);
}
return length;
}
static int getInitializerLength(FieldOrPropertyInitializer initializer)
{
// A constant field of type decimal needs a field initializer, so
// check if it is a metadata constant, not just a constant to exclude
// decimals. Other constants do not need field initializers.
if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant)
{
// ignore leading and trailing trivia of the node:
return initializer.Syntax.Span.Length;
}
return 0;
}
}
private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position)
{
// Search for the start of the span (the spans are non-overlapping and sorted)
int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos));
// Binary search returns non-negative result if the position is exactly the start of some span.
if (index >= 0)
{
return index;
}
// Otherwise, ~index is the closest span whose start is greater than the position.
// => Check if the preceding initializer span contains the position.
int precedingInitializerIndex = ~index - 1;
if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position))
{
return precedingInitializerIndex;
}
return -1;
}
public override IEnumerable<string> MemberNames
{
get
{
return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames;
}
}
internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered()
{
return GetTypeMembersDictionary().Flatten();
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance);
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
ImmutableArray<NamedTypeSymbol> members;
if (GetTypeMembersDictionary().TryGetValue(name, out members))
{
return members;
}
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity);
}
private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary()
{
if (_lazyTypeMembers == null)
{
var diagnostics = BindingDiagnosticBag.GetInstance();
if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null)
{
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.TypeMembers);
}
diagnostics.Free();
}
return _lazyTypeMembers;
}
private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics)
{
var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>();
try
{
foreach (var childDeclaration in declaration.Children)
{
var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics);
this.CheckMemberNameDistinctFromType(t, diagnostics);
var key = (t.Name, t.Arity);
SourceNamedTypeSymbol? other;
if (conflictDict.TryGetValue(key, out other))
{
if (Locations.Length == 1 || IsPartial)
{
if (t.IsPartial && other.IsPartial)
{
diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t);
}
else
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name);
}
}
}
else
{
conflictDict.Add(key, t);
}
symbols.Add(t);
}
if (IsInterface)
{
foreach (var t in symbols)
{
Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]);
}
}
Debug.Assert(s_emptyTypeMembers.Count == 0);
return symbols.Count > 0 ?
symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) :
s_emptyTypeMembers;
}
finally
{
symbols.Free();
}
}
private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics)
{
switch (this.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
if (member.Name == this.Name)
{
diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name);
}
break;
case TypeKind.Interface:
if (member.IsStatic)
{
goto case TypeKind.Class;
}
break;
}
}
internal override ImmutableArray<Symbol> GetMembersUnordered()
{
var result = _lazyMembersFlattened;
if (result.IsDefault)
{
result = GetMembersByName().Flatten(null); // do not sort.
ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result);
result = _lazyMembersFlattened;
}
return result.ConditionallyDeOrder();
}
public override ImmutableArray<Symbol> GetMembers()
{
if (_flags.FlattenedMembersIsSorted)
{
return _lazyMembersFlattened;
}
else
{
var allMembers = this.GetMembersUnordered();
if (allMembers.Length > 1)
{
// The array isn't sorted. Sort it and remember that we sorted it.
allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance);
ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers);
}
_flags.SetFlattenedMembersIsSorted();
return allMembers;
}
}
public sealed override ImmutableArray<Symbol> GetMembers(string name)
{
ImmutableArray<Symbol> members;
if (GetMembersByName().TryGetValue(name, out members))
{
return members;
}
return ImmutableArray<Symbol>.Empty;
}
/// <remarks>
/// For source symbols, there can only be a valid clone method if this is a record, which is a
/// simple syntax check. This will need to change when we generalize cloning, but it's a good
/// heuristic for now.
/// </remarks>
internal override bool HasPossibleWellKnownCloneMethod()
=> IsRecord;
internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name)
{
if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct)
{
return GetMembers(name);
}
return ImmutableArray<Symbol>.Empty;
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
if (this.TypeKind == TypeKind.Enum)
{
// For consistency with Dev10, emit value__ field first.
var valueField = ((SourceNamedTypeSymbol)this).EnumValueField;
RoslynDebug.Assert((object)valueField != null);
yield return valueField;
}
foreach (var m in this.GetMembers())
{
switch (m.Kind)
{
case SymbolKind.Field:
if (m is TupleErrorFieldSymbol)
{
break;
}
yield return (FieldSymbol)m;
break;
case SymbolKind.Event:
FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField;
if ((object?)associatedField != null)
{
yield return associatedField;
}
break;
}
}
}
/// <summary>
/// During early attribute decoding, we consider a safe subset of all members that will not
/// cause cyclic dependencies. Get all such members for this symbol.
///
/// In particular, this method will return nested types and fields (other than auto-property
/// backing fields).
/// </summary>
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return GetEarlyAttributeDecodingMembersDictionary().Flatten();
}
/// <summary>
/// During early attribute decoding, we consider a safe subset of all members that will not
/// cause cyclic dependencies. Get all such members for this symbol that have a particular name.
///
/// In particular, this method will return nested types and fields (other than auto-property
/// backing fields).
/// </summary>
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
ImmutableArray<Symbol> result;
return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty;
}
private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary()
{
if (_lazyEarlyAttributeDecodingMembersDictionary == null)
{
if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result)
{
return result;
}
var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached
// NOTE: members were added in a single pass over the syntax, so they're already
// in lexical order.
Dictionary<string, ImmutableArray<Symbol>> membersByName;
if (!membersAndInitializers.HaveIndexers)
{
membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name);
}
else
{
// We can't include indexer symbol yet, because we don't know
// what name it will have after attribute binding (because of
// IndexerNameAttribute).
membersByName = membersAndInitializers.NonTypeMembers.
WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)).
ToDictionary(s => s.Name);
}
AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary());
Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null);
}
return _lazyEarlyAttributeDecodingMembersDictionary;
}
// NOTE: this method should do as little work as possible
// we often need to get members just to do a lookup.
// All additional checks and diagnostics may be not
// needed yet or at all.
protected MembersAndInitializers GetMembersAndInitializers()
{
var membersAndInitializers = _lazyMembersAndInitializers;
if (membersAndInitializers != null)
{
return membersAndInitializers;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
membersAndInitializers = BuildMembersAndInitializers(diagnostics);
var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null);
if (alreadyKnown != null)
{
diagnostics.Free();
return alreadyKnown;
}
AddDeclarationDiagnostics(diagnostics);
diagnostics.Free();
_lazyDeclaredMembersAndInitializers = null;
return membersAndInitializers!;
}
/// <summary>
/// The purpose of this function is to assert that the <paramref name="member"/> symbol
/// is actually among the symbols cached by this type symbol in a way that ensures
/// that any consumer of standard APIs to get to type's members is going to get the same
/// symbol (same instance) for the member rather than an equivalent, but different instance.
/// </summary>
[Conditional("DEBUG")]
internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false)
{
if (member is FieldSymbol && forDiagnostics && this.IsTupleType)
{
// There is a problem with binding types of fields in tuple types.
// Skipping verification for them temporarily.
return;
}
if (member is NamedTypeSymbol type)
{
RoslynDebug.AssertOrFailFast(forDiagnostics);
RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true);
return;
}
else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol)
{
RoslynDebug.AssertOrFailFast(forDiagnostics);
return;
}
else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e)
{
RoslynDebug.AssertOrFailFast(forDiagnostics);
// Backing fields for field-like events are not added to the members list.
member = e;
}
var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers);
if (isMemberInCompleteMemberList(membersAndInitializers, member))
{
return;
}
if (membersAndInitializers is null)
{
if (member is SynthesizedSimpleProgramEntryPointSymbol)
{
RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member));
return;
}
var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers);
RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel);
if (declared is object)
{
if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member)
{
return;
}
}
else
{
// It looks like there was a race and we need to check _lazyMembersAndInitializers again
membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers);
RoslynDebug.AssertOrFailFast(membersAndInitializers is object);
if (isMemberInCompleteMemberList(membersAndInitializers, member))
{
return;
}
}
}
RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure.");
static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member)
{
return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true;
}
}
protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName()
{
if (this.state.HasComplete(CompletionPart.Members))
{
return _lazyMembersDictionary!;
}
return GetMembersByNameSlow();
}
private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow()
{
if (_lazyMembersDictionary == null)
{
var diagnostics = BindingDiagnosticBag.GetInstance();
var membersDictionary = MakeAllMembers(diagnostics);
if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null)
{
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.Members);
}
diagnostics.Free();
}
state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken));
return _lazyMembersDictionary;
}
internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents()
{
var membersAndInitializers = this.GetMembersAndInitializers();
return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent);
}
protected void AfterMembersChecks(BindingDiagnosticBag diagnostics)
{
if (IsInterface)
{
CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics);
}
CheckMemberNamesDistinctFromType(diagnostics);
CheckMemberNameConflicts(diagnostics);
CheckRecordMemberNames(diagnostics);
CheckSpecialMemberErrors(diagnostics);
CheckTypeParameterNameConflicts(diagnostics);
CheckAccessorNameConflicts(diagnostics);
bool unused = KnownCircularStruct;
CheckSequentialOnPartialType(diagnostics);
CheckForProtectedInStaticClass(diagnostics);
CheckForUnmatchedOperators(diagnostics);
var location = Locations[0];
var compilation = DeclaringCompilation;
if (this.IsRefLikeType)
{
compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (this.IsReadOnly)
{
compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true);
}
var baseType = BaseTypeNoUseSiteDiagnostics;
var interfaces = GetInterfacesToEmit();
// https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations.
if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger()))
{
compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (compilation.ShouldEmitNullableAttributes(this))
{
if (ShouldEmitNullableContextValue(out _))
{
compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute()))
{
compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true);
}
}
if (interfaces.Any(t => needsTupleElementNamesAttribute(t)))
{
// Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding)
// so the checking of all interfaces here involves some redundancy.
Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics);
}
bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate)
{
return ((object)baseType != null && predicate(baseType)) ||
interfaces.Any(predicate);
}
static bool needsTupleElementNamesAttribute(TypeSymbol type)
{
if (type is null)
{
return false;
}
var resultType = type.VisitType(
predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(),
arg: (object?)null);
return resultType is object;
}
}
private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics)
{
foreach (var member in GetMembersAndInitializers().NonTypeMembers)
{
CheckMemberNameDistinctFromType(member, diagnostics);
}
}
private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics)
{
if (declaration.Kind != DeclarationKind.Record &&
declaration.Kind != DeclarationKind.RecordStruct)
{
return;
}
foreach (var member in GetMembers("Clone"))
{
diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]);
}
}
private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics)
{
Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName();
// Collisions involving indexers are handled specially.
CheckIndexerNameConflicts(diagnostics, membersByName);
// key and value will be the same object in these dictionaries.
var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer);
var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer);
var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer);
// SPEC: The signature of an operator must differ from the signatures of all other
// SPEC: operators declared in the same class.
// DELIBERATE SPEC VIOLATION:
// The specification does not state that a user-defined conversion reserves the names
// op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt
// to define a field or a conflicting method with the metadata name of a user-defined
// conversion is an error. We preserve this reasonable behavior.
//
// Similarly, we treat "public static C operator +(C, C)" as colliding with
// "public static C op_Addition(C, C)". Fortunately, this behavior simply
// falls out of treating user-defined operators as ordinary methods; we do
// not need any special handling in this method.
//
// However, we must have special handling for conversions because conversions
// use a completely different rule for detecting collisions between two
// conversions: conversion signatures consist only of the source and target
// types of the conversions, and not the kind of the conversion (implicit or explicit),
// the name of the method, and so on.
//
// Therefore we must detect the following kinds of member name conflicts:
//
// 1. a method, conversion or field has the same name as a (different) field (* see note below)
// 2. a method has the same method signature as another method or conversion
// 3. a conversion has the same conversion signature as another conversion.
//
// However, we must *not* detect "a conversion has the same *method* signature
// as another conversion" because conversions are allowed to overload on
// return type but methods are not.
//
// (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for
// "non-method, non-conversion, non-type member", rather than spelling out
// "field, property or event...")
foreach (var pair in membersByName)
{
var name = pair.Key;
Symbol? lastSym = GetTypeMembers(name).FirstOrDefault();
methodsBySignature.Clear();
// Conversion collisions do not consider the name of the conversion,
// so do not clear that dictionary.
foreach (var symbol in pair.Value)
{
if (symbol.Kind == SymbolKind.NamedType ||
symbol.IsAccessor() ||
symbol.IsIndexer())
{
continue;
}
// We detect the first category of conflict by running down the list of members
// of the same name, and producing an error when we discover any of the following
// "bad transitions".
//
// * a method or conversion that comes after any field (not necessarily directly)
// * a field directly following a field
// * a field directly following a method or conversion
//
// Furthermore: we do not wish to detect collisions between nested types in
// this code; that is tested elsewhere. However, we do wish to detect a collision
// between a nested type and a field, method or conversion. Therefore we
// initialize our "bad transition" detector with a type of the given name,
// if there is one. That way we also detect the transitions of "method following
// type", and so on.
//
// The "lastSym" local below is used to detect these transitions. Its value is
// one of the following:
//
// * a nested type of the given name, or
// * the first method of the given name, or
// * the most recently processed field of the given name.
//
// If either the current symbol or the "last symbol" are not methods then
// there must be a collision:
//
// * if the current symbol is not a method and the last symbol is, then
// there is a field directly following a method of the same name
// * if the current symbol is a method and the last symbol is not, then
// there is a method directly or indirectly following a field of the same name,
// or a method of the same name as a nested type.
// * if neither are methods then either we have a field directly
// following a field of the same name, or a field and a nested type of the same name.
//
if (lastSym is object)
{
if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method)
{
if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name);
}
}
if (lastSym.Kind == SymbolKind.Method)
{
lastSym = symbol;
}
}
}
else
{
lastSym = symbol;
}
// That takes care of the first category of conflict; we detect the
// second and third categories as follows:
var conversion = symbol as SourceUserDefinedConversionSymbol;
var method = symbol as SourceMemberMethodSymbol;
if (!(conversion is null))
{
// Does this conversion collide *as a conversion* with any previously-seen
// conversion?
if (!conversionsAsConversions.Add(conversion))
{
// CS0557: Duplicate user-defined conversion in type 'C'
diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this);
}
else
{
// The other set might already contain a conversion which would collide
// *as a method* with the current conversion.
if (!conversionsAsMethods.ContainsKey(conversion))
{
conversionsAsMethods.Add(conversion, conversion);
}
}
// Does this conversion collide *as a method* with any previously-seen
// non-conversion method?
if (methodsBySignature.TryGetValue(conversion, out var previousMethod))
{
ReportMethodSignatureCollision(diagnostics, conversion, previousMethod);
}
// Do not add the conversion to the set of previously-seen methods; that set
// is only non-conversion methods.
}
else if (!(method is null))
{
// Does this method collide *as a method* with any previously-seen
// conversion?
if (conversionsAsMethods.TryGetValue(method, out var previousConversion))
{
ReportMethodSignatureCollision(diagnostics, method, previousConversion);
}
// Do not add the method to the set of previously-seen conversions.
// Does this method collide *as a method* with any previously-seen
// non-conversion method?
if (methodsBySignature.TryGetValue(method, out var previousMethod))
{
ReportMethodSignatureCollision(diagnostics, method, previousMethod);
}
else
{
// We haven't seen this method before. Make a note of it in case
// we see a colliding method later.
methodsBySignature.Add(method, method);
}
}
}
}
}
// Report a name conflict; the error is reported on the location of method1.
// UNDONE: Consider adding a secondary location pointing to the second method.
private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2)
{
switch (method1, method2)
{
case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }):
case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }):
// these could be 2 parts of the same partial method.
// Partial methods are allowed to collide by signature.
return;
case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }):
return;
}
// If method1 is a constructor only because its return type is missing, then
// we've already produced a diagnostic for the missing return type and we suppress the
// diagnostic about duplicate signature.
if (method1.MethodKind == MethodKind.Constructor &&
((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name)
{
return;
}
Debug.Assert(method1.ParameterCount == method2.ParameterCount);
for (int i = 0; i < method1.ParameterCount; i++)
{
var refKind1 = method1.Parameters[i].RefKind;
var refKind2 = method2.Parameters[i].RefKind;
if (refKind1 != refKind2)
{
// '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}'
var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD;
diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString());
return;
}
}
// Special case: if there are two destructors, use the destructor syntax instead of "Finalize"
var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ?
"~" + this.Name :
(method1.IsConstructor() ? this.Name : method1.Name);
// Type '{1}' already defines a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this);
}
private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName)
{
PooledHashSet<string>? typeParameterNames = null;
if (this.Arity > 0)
{
typeParameterNames = PooledHashSet<string>.GetInstance();
foreach (TypeParameterSymbol typeParameter in this.TypeParameters)
{
typeParameterNames.Add(typeParameter.Name);
}
}
var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer);
// Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because
// they may be explicit interface implementations.
foreach (var members in membersByName.Values)
{
string? lastIndexerName = null;
indexersBySignature.Clear();
foreach (var symbol in members)
{
if (symbol.IsIndexer())
{
PropertySymbol indexer = (PropertySymbol)symbol;
CheckIndexerSignatureCollisions(
indexer,
diagnostics,
membersByName,
indexersBySignature,
ref lastIndexerName);
// Also check for collisions with type parameters, which aren't in the member map.
// NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts.
if (typeParameterNames != null)
{
string indexerName = indexer.MetadataName;
if (typeParameterNames.Contains(indexerName))
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName);
continue;
}
}
}
}
}
typeParameterNames?.Free();
}
private void CheckIndexerSignatureCollisions(
PropertySymbol indexer,
BindingDiagnosticBag diagnostics,
Dictionary<string, ImmutableArray<Symbol>> membersByName,
Dictionary<PropertySymbol, PropertySymbol> indexersBySignature,
ref string? lastIndexerName)
{
if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked
{
string indexerName = indexer.MetadataName;
if (lastIndexerName != null && lastIndexerName != indexerName)
{
// NOTE: dev10 checks indexer names by comparing each to the previous.
// For example, if indexers are declared with names A, B, A, B, then there
// will be three errors - one for each time the name is different from the
// previous one. If, on the other hand, the names are A, A, B, B, then
// there will only be one error because only one indexer has a different
// name from the previous one.
diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]);
}
lastIndexerName = indexerName;
if (Locations.Length == 1 || IsPartial)
{
if (membersByName.ContainsKey(indexerName))
{
// The name of the indexer is reserved - it can only be used by other indexers.
Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer));
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName);
}
}
}
if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature))
{
// Type '{1}' already defines a member called '{0}' with the same parameter types
// NOTE: Dev10 prints "this" as the name of the indexer.
diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this);
}
else
{
indexersBySignature[indexer] = indexer;
}
}
private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics)
{
var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary);
foreach (var member in this.GetMembersUnordered())
{
member.AfterAddingTypeMembersChecks(conversions, diagnostics);
}
}
private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics)
{
if (this.TypeKind == TypeKind.Delegate)
{
// Delegates do not have conflicts between their type parameter
// names and their methods; it is legal (though odd) to say
// delegate void D<Invoke>(Invoke x);
return;
}
if (Locations.Length == 1 || IsPartial)
{
foreach (var tp in TypeParameters)
{
foreach (var dup in GetMembers(tp.Name))
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name);
}
}
}
}
private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics)
{
// Report errors where property and event accessors
// conflict with other members of the same name.
foreach (Symbol symbol in this.GetMembersUnordered())
{
if (symbol.IsExplicitInterfaceImplementation())
{
// If there's a name conflict it will show up as a more specific
// interface implementation error.
continue;
}
switch (symbol.Kind)
{
case SymbolKind.Property:
{
var propertySymbol = (PropertySymbol)symbol;
this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics);
this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics);
break;
}
case SymbolKind.Event:
{
var eventSymbol = (EventSymbol)symbol;
this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics);
this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics);
break;
}
}
}
}
internal override bool KnownCircularStruct
{
get
{
if (_lazyKnownCircularStruct == (int)ThreeState.Unknown)
{
if (TypeKind != TypeKind.Struct)
{
Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown);
}
else
{
var diagnostics = BindingDiagnosticBag.GetInstance();
var value = (int)CheckStructCircularity(diagnostics).ToThreeState();
if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown)
{
AddDeclarationDiagnostics(diagnostics);
}
Debug.Assert(value == _lazyKnownCircularStruct);
diagnostics.Free();
}
}
return _lazyKnownCircularStruct == (int)ThreeState.True;
}
}
private bool CheckStructCircularity(BindingDiagnosticBag diagnostics)
{
Debug.Assert(TypeKind == TypeKind.Struct);
CheckFiniteFlatteningGraph(diagnostics);
return HasStructCircularity(diagnostics);
}
private bool HasStructCircularity(BindingDiagnosticBag diagnostics)
{
foreach (var valuesByName in GetMembersByName().Values)
{
foreach (var member in valuesByName)
{
if (member.Kind != SymbolKind.Field)
{
// NOTE: don't have to check field-like events, because they can't have struct types.
continue;
}
var field = (FieldSymbol)member;
if (field.IsStatic)
{
continue;
}
var type = field.NonPointerType();
if (((object)type != null) &&
(type.TypeKind == TypeKind.Struct) &&
BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) &&
!type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type
{
// If this is a backing field, report the error on the associated property.
var symbol = field.AssociatedSymbol ?? field;
if (symbol.Kind == SymbolKind.Parameter)
{
// We should stick to members for this error.
symbol = field;
}
// Struct member '{0}' of type '{1}' causes a cycle in the struct layout
diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type);
return true;
}
}
}
return false;
}
private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics)
{
if (!IsStatic)
{
return;
}
// no protected members allowed
foreach (var valuesByName in GetMembersByName().Values)
{
foreach (var member in valuesByName)
{
if (member is TypeSymbol)
{
// Duplicate Dev10's failure to diagnose this error.
continue;
}
if (member.DeclaredAccessibility.HasProtected())
{
if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor)
{
diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member);
}
}
}
}
}
private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics)
{
// SPEC: The true and false unary operators require pairwise declaration.
// SPEC: A compile-time error occurs if a class or struct declares one
// SPEC: of these operators without also declaring the other.
//
// SPEC DEFICIENCY: The line of the specification quoted above should say
// the same thing as the lines below: that the formal parameters of the
// paired true/false operators must match exactly. You can't do
// op true(S) and op false(S?) for example.
// SPEC: Certain binary operators require pairwise declaration. For every
// SPEC: declaration of either operator of a pair, there must be a matching
// SPEC: declaration of the other operator of the pair. Two operator
// SPEC: declarations match when they have the same return type and the same
// SPEC: type for each parameter. The following operators require pairwise
// SPEC: declaration: == and !=, > and <, >= and <=.
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName);
// We also produce a warning if == / != is overridden without also overriding
// Equals and GetHashCode, or if Equals is overridden without GetHashCode.
CheckForEqualityAndGetHashCode(diagnostics);
}
private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2)
{
var ops1 = this.GetOperators(operatorName1);
var ops2 = this.GetOperators(operatorName2);
CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2);
CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1);
}
private static void CheckForUnmatchedOperator(
BindingDiagnosticBag diagnostics,
ImmutableArray<MethodSymbol> ops1,
ImmutableArray<MethodSymbol> ops2,
string operatorName2)
{
foreach (var op1 in ops1)
{
bool foundMatch = false;
foreach (var op2 in ops2)
{
foundMatch = DoOperatorsPair(op1, op2);
if (foundMatch)
{
break;
}
}
if (!foundMatch)
{
// CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined
diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1,
SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2)));
}
}
}
private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2)
{
if (op1.ParameterCount != op2.ParameterCount)
{
return false;
}
for (int p = 0; p < op1.ParameterCount; ++p)
{
if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions))
{
return false;
}
}
if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
return true;
}
private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics)
{
if (this.IsInterfaceType())
{
// Interfaces are allowed to define Equals without GetHashCode if they want.
return;
}
if (IsRecord || IsRecordStruct)
{
// For records the warnings reported below are simply going to echo record specific errors,
// producing more noise.
return;
}
bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() ||
this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any();
bool overridesEquals = this.TypeOverridesObjectMethod("Equals");
if (hasOp || overridesEquals)
{
bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode");
if (overridesEquals && !overridesGHC)
{
// CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode()
diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this);
}
if (hasOp && !overridesEquals)
{
// CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o)
diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this);
}
if (hasOp && !overridesGHC)
{
// CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode()
diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this);
}
}
}
private bool TypeOverridesObjectMethod(string name)
{
foreach (var method in this.GetMembers(name).OfType<MethodSymbol>())
{
if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object)
{
return true;
}
}
return false;
}
private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics)
{
Debug.Assert(ReferenceEquals(this, this.OriginalDefinition));
if (AllTypeArgumentCount() == 0) return;
var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance);
instanceMap.Add(this, this);
foreach (var m in this.GetMembersUnordered())
{
var f = m as FieldSymbol;
if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue;
var type = (NamedTypeSymbol)f.Type;
if (InfiniteFlatteningGraph(this, type, instanceMap))
{
// Struct member '{0}' of type '{1}' causes a cycle in the struct layout
diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type);
//this.KnownCircularStruct = true;
return;
}
}
}
private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap)
{
if (!t.ContainsTypeParameter()) return false;
var tOriginal = t.OriginalDefinition;
if (instanceMap.TryGetValue(tOriginal, out var oldInstance))
{
// short circuit when we find a cycle, but only return true when the cycle contains the top struct
return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top);
}
else
{
instanceMap.Add(tOriginal, t);
try
{
foreach (var m in t.GetMembersUnordered())
{
var f = m as FieldSymbol;
if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue;
var type = (NamedTypeSymbol)f.Type;
if (InfiniteFlatteningGraph(top, type, instanceMap)) return true;
}
return false;
}
finally
{
instanceMap.Remove(tOriginal);
}
}
}
private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics)
{
if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential)
{
return;
}
SyntaxReference? whereFoundField = null;
if (this.SyntaxReferences.Length <= 1)
{
return;
}
foreach (var syntaxRef in this.SyntaxReferences)
{
var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax;
if (syntax == null)
{
continue;
}
foreach (var m in syntax.Members)
{
if (HasInstanceData(m))
{
if (whereFoundField != null && whereFoundField != syntaxRef)
{
diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this);
return;
}
whereFoundField = syntaxRef;
}
}
}
}
private static bool HasInstanceData(MemberDeclarationSyntax m)
{
switch (m.Kind())
{
case SyntaxKind.FieldDeclaration:
var fieldDecl = (FieldDeclarationSyntax)m;
return
!ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword);
case SyntaxKind.PropertyDeclaration:
// auto-property
var propertyDecl = (PropertyDeclarationSyntax)m;
return
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) &&
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) &&
propertyDecl.AccessorList != null &&
All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null);
case SyntaxKind.EventFieldDeclaration:
// field-like event declaration
var eventFieldDecl = (EventFieldDeclarationSyntax)m;
return
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) &&
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword);
default:
return false;
}
}
private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode
{
foreach (var t in list) { if (predicate(t)) return true; };
return false;
}
private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier)
{
foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; };
return false;
}
private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics)
{
Dictionary<string, ImmutableArray<Symbol>> membersByName;
var membersAndInitializers = GetMembersAndInitializers();
// Most types don't have indexers. If this is one of those types,
// just reuse the dictionary we build for early attribute decoding.
// For tuples, we also need to take the slow path.
if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object)
{
membersByName = _lazyEarlyAttributeDecodingMembersDictionary;
}
else
{
membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance);
// Merge types into the member dictionary
AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary());
}
MergePartialMembers(ref membersByName, diagnostics);
return membersByName;
}
private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName)
{
foreach (var pair in typesByName)
{
string name = pair.Key;
ImmutableArray<NamedTypeSymbol> types = pair.Value;
ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types);
ImmutableArray<Symbol> membersForName;
if (membersByName.TryGetValue(name, out membersForName))
{
membersByName[name] = membersForName.Concat(typesAsSymbols);
}
else
{
membersByName.Add(name, typesAsSymbols);
}
}
}
private sealed class DeclaredMembersAndInitializersBuilder
{
public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance();
public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance();
public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance();
public bool HaveIndexers;
public RecordDeclarationSyntax? RecordDeclarationWithParameters;
public SynthesizedRecordConstructor? RecordPrimaryConstructor;
public bool IsNullableEnabledForInstanceConstructorsAndFields;
public bool IsNullableEnabledForStaticConstructorsAndFields;
public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation)
{
return new DeclaredMembersAndInitializers(
NonTypeMembers.ToImmutableAndFree(),
MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers),
MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers),
HaveIndexers,
RecordDeclarationWithParameters,
RecordPrimaryConstructor,
isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields,
isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields,
compilation);
}
public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax)
{
ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic);
isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax);
}
public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value)
{
ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic);
isNullableEnabled = isNullableEnabled || value;
}
private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic)
{
return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields;
}
public void Free()
{
NonTypeMembers.Free();
foreach (var group in StaticInitializers)
{
group.Free();
}
StaticInitializers.Free();
foreach (var group in InstanceInitializers)
{
group.Free();
}
InstanceInitializers.Free();
}
internal void AddOrWrapTupleMembers(SourceMemberContainerTypeSymbol type)
{
this.NonTypeMembers = type.AddOrWrapTupleMembers(this.NonTypeMembers.ToImmutableAndFree());
}
}
protected sealed class DeclaredMembersAndInitializers
{
public readonly ImmutableArray<Symbol> NonTypeMembers;
public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers;
public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers;
public readonly bool HaveIndexers;
public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters;
public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor;
public readonly bool IsNullableEnabledForInstanceConstructorsAndFields;
public readonly bool IsNullableEnabledForStaticConstructorsAndFields;
public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers();
private DeclaredMembersAndInitializers()
{
}
public DeclaredMembersAndInitializers(
ImmutableArray<Symbol> nonTypeMembers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers,
bool haveIndexers,
RecordDeclarationSyntax? recordDeclarationWithParameters,
SynthesizedRecordConstructor? recordPrimaryConstructor,
bool isNullableEnabledForInstanceConstructorsAndFields,
bool isNullableEnabledForStaticConstructorsAndFields,
CSharpCompilation compilation)
{
Debug.Assert(!nonTypeMembers.IsDefault);
AssertInitializers(staticInitializers, compilation);
AssertInitializers(instanceInitializers, compilation);
Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol));
Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object);
this.NonTypeMembers = nonTypeMembers;
this.StaticInitializers = staticInitializers;
this.InstanceInitializers = instanceInitializers;
this.HaveIndexers = haveIndexers;
this.RecordDeclarationWithParameters = recordDeclarationWithParameters;
this.RecordPrimaryConstructor = recordPrimaryConstructor;
this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields;
this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields;
}
[Conditional("DEBUG")]
public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation)
{
Debug.Assert(!initializers.IsDefault);
if (initializers.IsEmpty)
{
return;
}
foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers)
{
Debug.Assert(!group.IsDefaultOrEmpty);
}
for (int i = 0; i < initializers.Length; i++)
{
if (i > 0)
{
Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0);
}
if (i + 1 < initializers.Length)
{
Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0);
}
if (initializers[i].Length != 1)
{
Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0);
}
}
}
}
private sealed class MembersAndInitializersBuilder
{
public ArrayBuilder<Symbol>? NonTypeMembers;
private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers;
private bool IsNullableEnabledForInstanceConstructorsAndFields;
private bool IsNullableEnabledForStaticConstructorsAndFields;
public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers)
{
Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel);
this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields;
this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields;
}
public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers)
{
var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers;
var instanceInitializers = InstanceInitializersForPositionalMembers is null
? declaredMembers.InstanceInitializers
: mergeInitializers();
return new MembersAndInitializers(
nonTypeMembers,
declaredMembers.StaticInitializers,
instanceInitializers,
declaredMembers.HaveIndexers,
isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields,
isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields);
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers()
{
Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0);
Debug.Assert(declaredMembers.RecordPrimaryConstructor is object);
Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object);
Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree);
Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start));
var groupCount = declaredMembers.InstanceInitializers.Length;
if (groupCount == 0)
{
return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree());
}
var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation;
var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation);
int insertAt;
for (insertAt = 0; insertAt < groupCount; insertAt++)
{
if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0)
{
break;
}
}
ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder;
if (insertAt != groupCount &&
declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree &&
declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start))
{
// Need to merge into the previous group
var declaredInitializers = declaredMembers.InstanceInitializers[insertAt];
var insertedInitializers = InstanceInitializersForPositionalMembers;
#if DEBUG
// initializers should be added in syntax order:
Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree);
Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start);
#endif
insertedInitializers.AddRange(declaredInitializers);
groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount);
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt);
groupsBuilder.Add(insertedInitializers.ToImmutableAndFree());
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1));
Debug.Assert(groupsBuilder.Count == groupCount);
}
else
{
Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree &&
declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start)));
groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1);
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt);
groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree());
groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt);
Debug.Assert(groupsBuilder.Count == groupCount + 1);
}
var result = groupsBuilder.ToImmutableAndFree();
DeclaredMembersAndInitializers.AssertInitializers(result, compilation);
return result;
}
}
public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer)
{
if (InstanceInitializersForPositionalMembers is null)
{
InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance();
}
InstanceInitializersForPositionalMembers.Add(initializer);
}
public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers)
{
return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers;
}
public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers)
{
if (NonTypeMembers is null)
{
NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1);
NonTypeMembers.AddRange(declaredMembers.NonTypeMembers);
}
NonTypeMembers.Add(member);
}
public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax)
{
ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic);
isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax);
}
private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic)
{
return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields;
}
internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers)
{
if (initializers.Count == 0)
{
initializers.Free();
return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty;
}
var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count);
foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers)
{
builder.Add(group.ToImmutableAndFree());
}
initializers.Free();
return builder.ToImmutableAndFree();
}
public void Free()
{
NonTypeMembers?.Free();
InstanceInitializersForPositionalMembers?.Free();
}
}
private MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics)
{
var declaredMembersAndInitializers = getDeclaredMembersAndInitializers();
if (declaredMembersAndInitializers is null)
{
// Another thread completed the work before this one
return null;
}
var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers);
AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics);
if (Volatile.Read(ref _lazyMembersAndInitializers) != null)
{
// Another thread completed the work before this one
membersAndInitializersBuilder.Free();
return null;
}
return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers);
DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers()
{
var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers;
if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel)
{
return declaredMembersAndInitializers;
}
if (Volatile.Read(ref _lazyMembersAndInitializers) is not null)
{
// We're previously computed declared members and already cleared them out
// No need to compute them again
return null;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics);
var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel);
if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel)
{
diagnostics.Free();
return alreadyKnown;
}
AddDeclarationDiagnostics(diagnostics);
diagnostics.Free();
return declaredMembersAndInitializers!;
}
// Builds explicitly declared members (as opposed to synthesized members).
// This should not attempt to bind any method parameters as that would cause
// the members being built to be captured in the binder cache before the final
// list of members is determined.
DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics)
{
var builder = new DeclaredMembersAndInitializersBuilder();
AddDeclaredNontypeMembers(builder, diagnostics);
switch (TypeKind)
{
case TypeKind.Struct:
CheckForStructBadInitializers(builder, diagnostics);
CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics);
break;
case TypeKind.Enum:
CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics);
break;
case TypeKind.Class:
case TypeKind.Interface:
case TypeKind.Submission:
// No additional checking required.
break;
default:
break;
}
if (IsTupleType)
{
builder.AddOrWrapTupleMembers(this);
}
if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel)
{
// _lazyDeclaredMembersAndInitializers is already computed. no point to continue.
builder.Free();
return null;
}
return builder.ToReadOnlyAndFree(DeclaringCompilation);
}
}
internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints()
{
if (_lazySimpleProgramEntryPoints.IsDefault)
{
var diagnostics = BindingDiagnosticBag.GetInstance();
var simpleProgramEntryPoints = buildSimpleProgramEntryPoint(diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazySimpleProgramEntryPoints, simpleProgramEntryPoints))
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
Debug.Assert(!_lazySimpleProgramEntryPoints.IsDefault);
return _lazySimpleProgramEntryPoints;
ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics)
{
if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true }
|| this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName)
{
return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty;
}
ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null;
foreach (var singleDecl in declaration.Declarations)
{
if (singleDecl.IsSimpleProgram)
{
if (builder is null)
{
builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance();
}
else
{
Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation);
}
builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics));
}
}
if (builder is null)
{
return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty;
}
return builder.ToImmutableAndFree();
}
}
private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics)
{
if (TypeKind is TypeKind.Class)
{
AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers);
}
switch (TypeKind)
{
case TypeKind.Struct:
case TypeKind.Enum:
case TypeKind.Class:
case TypeKind.Interface:
case TypeKind.Submission:
AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics);
AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics);
break;
default:
break;
}
}
private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics)
{
foreach (var decl in this.declaration.Declarations)
{
if (!decl.HasAnyNontypeMembers)
{
continue;
}
if (_lazyMembersAndInitializers != null)
{
// membersAndInitializers is already computed. no point to continue.
return;
}
var syntax = decl.SyntaxReference.GetSyntax();
switch (syntax.Kind())
{
case SyntaxKind.EnumDeclaration:
AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics);
break;
case SyntaxKind.DelegateDeclaration:
SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics);
break;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
// The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit.
AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics);
break;
case SyntaxKind.CompilationUnit:
AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics);
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
var typeDecl = (TypeDeclarationSyntax)syntax;
AddNonTypeMembers(builder, typeDecl.Members, diagnostics);
break;
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
var recordDecl = (RecordDeclarationSyntax)syntax;
var parameterList = recordDecl.ParameterList;
noteRecordParameters(recordDecl, parameterList, builder, diagnostics);
AddNonTypeMembers(builder, recordDecl.Members, diagnostics);
break;
default:
throw ExceptionUtilities.UnexpectedValue(syntax.Kind());
}
}
void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics)
{
if (parameterList is null)
{
return;
}
if (builder.RecordDeclarationWithParameters is null)
{
builder.RecordDeclarationWithParameters = syntax;
var ctor = new SynthesizedRecordConstructor(this, syntax);
builder.RecordPrimaryConstructor = ctor;
var compilation = DeclaringCompilation;
builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList);
if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } })
{
builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList);
}
}
else
{
diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location);
}
}
}
internal Binder GetBinder(CSharpSyntaxNode syntaxNode)
{
return this.DeclaringCompilation.GetBinder(syntaxNode);
}
private void MergePartialMembers(
ref Dictionary<string, ImmutableArray<Symbol>> membersByName,
BindingDiagnosticBag diagnostics)
{
var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count);
memberNames.AddRange(membersByName.Keys);
//key and value will be the same object
var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer);
foreach (var name in memberNames)
{
methodsBySignature.Clear();
foreach (var symbol in membersByName[name])
{
var method = symbol as SourceMemberMethodSymbol;
if (method is null || !method.IsPartial)
{
continue; // only partial methods need to be merged
}
if (methodsBySignature.TryGetValue(method, out var prev))
{
var prevPart = (SourceOrdinaryMethodSymbol)prev;
var methodPart = (SourceOrdinaryMethodSymbol)method;
if (methodPart.IsPartialImplementation &&
(prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart)))
{
// A partial method may not have multiple implementing declarations
diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]);
}
else if (methodPart.IsPartialDefinition &&
(prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart)))
{
// A partial method may not have multiple defining declarations
diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]);
}
else
{
if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary)
{
// Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel.
membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName);
}
membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart);
}
}
else
{
methodsBySignature.Add(method, method);
}
}
foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values)
{
// partial implementations not paired with a definition
if (method.IsPartialImplementation && method.OtherPartOfPartial is null)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method);
}
else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true })
{
diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method);
}
}
}
memberNames.Free();
}
/// <summary>
/// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name),
/// and returning the combined symbol.
/// </summary>
/// <param name="symbols">The symbols array containing both the latent and implementing declaration</param>
/// <param name="part1">One of the two declarations</param>
/// <param name="part2">The other declaration</param>
/// <returns>An updated symbols array containing only one method symbol representing the two parts</returns>
private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2)
{
SourceOrdinaryMethodSymbol definition;
SourceOrdinaryMethodSymbol implementation;
if (part1.IsPartialDefinition)
{
definition = part1;
implementation = part2;
}
else
{
definition = part2;
implementation = part1;
}
SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation);
// a partial method is represented in the member list by its definition part:
return Remove(symbols, implementation);
}
private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol)
{
var builder = ArrayBuilder<Symbol>.GetInstance();
foreach (var s in symbols)
{
if (!ReferenceEquals(s, symbol))
{
builder.Add(s);
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Report an error if a member (other than a method) exists with the same name
/// as the property accessor, or if a method exists with the same name and signature.
/// </summary>
private void CheckForMemberConflictWithPropertyAccessor(
PropertySymbol propertySymbol,
bool getNotSet,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller
MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod;
string accessorName;
if ((object)accessor != null)
{
accessorName = accessor.Name;
}
else
{
string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name;
accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName,
getNotSet,
propertySymbol.IsCompilationOutputWinMdObj());
}
foreach (var symbol in GetMembers(accessorName))
{
if (symbol.Kind != SymbolKind.Method)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName);
return;
}
else
{
var methodSymbol = (MethodSymbol)symbol;
if ((methodSymbol.MethodKind == MethodKind.Ordinary) &&
ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters))
{
// Type '{1}' already reserves a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this);
return;
}
}
}
}
/// <summary>
/// Report an error if a member (other than a method) exists with the same name
/// as the event accessor, or if a method exists with the same name and signature.
/// </summary>
private void CheckForMemberConflictWithEventAccessor(
EventSymbol eventSymbol,
bool isAdder,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller
string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder);
foreach (var symbol in GetMembers(accessorName))
{
if (symbol.Kind != SymbolKind.Method)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName);
return;
}
else
{
var methodSymbol = (MethodSymbol)symbol;
if ((methodSymbol.MethodKind == MethodKind.Ordinary) &&
ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters))
{
// Type '{1}' already reserves a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this);
return;
}
}
}
}
/// <summary>
/// Return the location of the accessor, or if no accessor, the location of the property.
/// </summary>
private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet)
{
var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol;
return locationFrom.Locations[0];
}
/// <summary>
/// Return the location of the accessor, or if no accessor, the location of the event.
/// </summary>
private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder)
{
var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol;
return locationFrom.Locations[0];
}
/// <summary>
/// Return true if the method parameters match the parameters of the
/// property accessor, including the value parameter for the setter.
/// </summary>
private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams)
{
var propertyParams = propertySymbol.Parameters;
var numParams = propertyParams.Length + (getNotSet ? 0 : 1);
if (numParams != methodParams.Length)
{
return false;
}
for (int i = 0; i < numParams; i++)
{
var methodParam = methodParams[i];
if (methodParam.RefKind != RefKind.None)
{
return false;
}
var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type;
if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
}
return true;
}
/// <summary>
/// Return true if the method parameters match the parameters of the
/// event accessor, including the value parameter.
/// </summary>
private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams)
{
return
methodParams.Length == 1 &&
methodParams[0].RefKind == RefKind.None &&
eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions);
}
private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics)
{
// The previous enum constant used to calculate subsequent
// implicit enum constants. (This is the most recent explicit
// enum constant or the first implicit constant if no explicit values.)
SourceEnumConstantSymbol? otherSymbol = null;
// Offset from "otherSymbol".
int otherSymbolOffset = 0;
foreach (var member in syntax.Members)
{
SourceEnumConstantSymbol symbol;
var valueOpt = member.EqualsValue;
if (valueOpt != null)
{
symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics);
}
else
{
symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics);
}
result.NonTypeMembers.Add(symbol);
if (valueOpt != null || otherSymbol is null)
{
otherSymbol = symbol;
otherSymbolOffset = 1;
}
else
{
otherSymbolOffset++;
}
}
}
private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node)
{
if (initializers == null)
{
initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance();
}
else if (initializers.Count != 0)
{
// initializers should be added in syntax order:
Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree);
Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start);
}
initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node));
}
private static void AddInitializers(
ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers,
ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt)
{
if (siblingsOpt != null)
{
allInitializers.Add(siblingsOpt);
}
}
private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics)
{
foreach (var member in nonTypeMembers)
{
CheckInterfaceMember(member, diagnostics);
}
}
private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics)
{
switch (member.Kind)
{
case SymbolKind.Field:
break;
case SymbolKind.Method:
var meth = (MethodSymbol)member;
switch (meth.MethodKind)
{
case MethodKind.Constructor:
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]);
break;
case MethodKind.Conversion:
if (!meth.IsAbstract)
{
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]);
}
break;
case MethodKind.UserDefinedOperator:
if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName))
{
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]);
}
break;
case MethodKind.Destructor:
diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]);
break;
case MethodKind.ExplicitInterfaceImplementation:
//CS0541 is handled in SourcePropertySymbol
case MethodKind.Ordinary:
case MethodKind.LocalFunction:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.EventAdd:
case MethodKind.EventRemove:
case MethodKind.StaticConstructor:
break;
default:
throw ExceptionUtilities.UnexpectedValue(meth.MethodKind);
}
break;
case SymbolKind.Property:
break;
case SymbolKind.Event:
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
private static void CheckForStructDefaultConstructors(
ArrayBuilder<Symbol> members,
bool isEnum,
BindingDiagnosticBag diagnostics)
{
foreach (var s in members)
{
var m = s as MethodSymbol;
if (!(m is null))
{
if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0)
{
var location = m.Locations[0];
if (isEnum)
{
diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location);
}
else
{
MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location);
if (m.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location);
}
}
}
}
}
}
private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics)
{
Debug.Assert(TypeKind == TypeKind.Struct);
if (builder.RecordDeclarationWithParameters is not null)
{
Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record
&& record.Kind() == SyntaxKind.RecordStructDeclaration);
return;
}
foreach (var initializers in builder.InstanceInitializers)
{
foreach (FieldOrPropertyInitializer initializer in initializers)
{
var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt;
MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]);
}
}
}
private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers)
{
var simpleProgramEntryPoints = GetSimpleProgramEntryPoints();
foreach (var member in simpleProgramEntryPoints)
{
builder.AddNonTypeMember(member, declaredMembersAndInitializers);
}
}
private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics)
{
if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct))
{
return;
}
ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList;
var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate();
var fieldsByName = PooledDictionary<string, Symbol>.GetInstance();
var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers);
var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1);
var memberNames = PooledHashSet<string>.GetInstance();
foreach (var member in membersSoFar)
{
memberNames.Add(member.Name);
switch (member)
{
case EventSymbol:
case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }:
continue;
case FieldSymbol { Name: var fieldName }:
if (!fieldsByName.ContainsKey(fieldName))
{
fieldsByName.Add(fieldName, member);
}
continue;
}
if (!memberSignatures.ContainsKey(member))
{
memberSignatures.Add(member, member);
}
}
CSharpCompilation compilation = this.DeclaringCompilation;
bool isRecordClass = declaration.Kind == DeclarationKind.Record;
// Positional record
bool primaryAndCopyCtorAmbiguity = false;
if (!(paramList is null))
{
Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object);
// primary ctor
var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor;
Debug.Assert(ctor is object);
members.Add(ctor);
if (ctor.ParameterCount != 0)
{
// properties and Deconstruct
var existingOrAddedMembers = addProperties(ctor.Parameters);
addDeconstruct(ctor, existingOrAddedMembers);
}
if (isRecordClass)
{
primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions);
}
}
if (isRecordClass)
{
addCopyCtor(primaryAndCopyCtorAmbiguity);
addCloneMethod();
}
PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null;
var thisEquals = addThisEquals(equalityContract);
if (isRecordClass)
{
addBaseEquals();
}
addObjectEquals(thisEquals);
var getHashCode = addGetHashCode(equalityContract);
addEqualityOperators();
if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode)
{
diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name);
}
var printMembers = addPrintMembersMethod(membersSoFar);
addToStringMethod(printMembers);
memberSignatures.Free();
fieldsByName.Free();
memberNames.Free();
// Synthesizing non-readonly properties in struct would require changing readonly logic for PrintMembers method synthesis
Debug.Assert(isRecordClass || !members.Any(m => m is PropertySymbol { GetMethod.IsEffectivelyReadOnly: false }));
// We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all
// going to the record declaration
members.AddRange(membersSoFar);
builder.NonTypeMembers?.Free();
builder.NonTypeMembers = members;
return;
void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers)
{
Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol));
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.DeconstructMethodName,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations,
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.Out
)),
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod))
{
members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics));
}
else
{
var deconstruct = (MethodSymbol)existingDeconstructMethod;
if (deconstruct.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct);
}
if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType);
}
if (deconstruct.IsStatic)
{
diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct);
}
}
}
void addCopyCtor(bool primaryAndCopyCtorAmbiguity)
{
Debug.Assert(isRecordClass);
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.InstanceConstructorName,
this,
MethodKind.Constructor,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(this),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.None
)),
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor))
{
var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count);
members.Add(copyCtor);
if (primaryAndCopyCtorAmbiguity)
{
diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]);
}
}
else
{
var constructor = (MethodSymbol)existingConstructor;
if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected))
{
diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor);
}
}
}
void addCloneMethod()
{
Debug.Assert(isRecordClass);
members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics));
}
MethodSymbol addPrintMembersMethod(IEnumerable<Symbol> userDefinedMembers)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.PrintMembersMethodName,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.None)),
RefKind.None,
isInitOnly: false,
isStatic: false,
returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)),
refCustomModifiers: ImmutableArray<CustomModifier>.Empty,
explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty);
MethodSymbol printMembersMethod;
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod))
{
printMembersMethod = new SynthesizedRecordPrintMembers(this, userDefinedMembers, memberOffset: members.Count, diagnostics);
members.Add(printMembersMethod);
}
else
{
printMembersMethod = (MethodSymbol)existingPrintMembersMethod;
if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()))
{
if (printMembersMethod.DeclaredAccessibility != Accessibility.Private)
{
diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod);
}
}
else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected)
{
diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod);
}
if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions))
{
if (!printMembersMethod.ReturnType.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType);
}
}
else if (isRecordClass)
{
SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics);
}
reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics);
}
return printMembersMethod;
}
void addToStringMethod(MethodSymbol printMethod)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.ObjectToString,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
isInitOnly: false,
isStatic: false,
returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)),
refCustomModifiers: ImmutableArray<CustomModifier>.Empty,
explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty);
var baseToStringMethod = getBaseToStringMethod();
if (baseToStringMethod is { IsSealed: true })
{
if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord))
{
var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion;
var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion();
diagnostics.Add(
ErrorCode.ERR_InheritingFromRecordWithSealedToString,
this.Locations[0],
languageVersion.ToDisplayString(),
new CSharpRequiredLanguageVersion(requiredVersion));
}
}
else
{
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod))
{
var toStringMethod = new SynthesizedRecordToString(
this,
printMethod,
memberOffset: members.Count,
isReadOnly: printMethod.IsEffectivelyReadOnly,
diagnostics);
members.Add(toStringMethod);
}
else
{
var toStringMethod = (MethodSymbol)existingToStringMethod;
if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed)
{
MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability(
diagnostics,
this.DeclaringCompilation,
toStringMethod.Locations[0]);
}
}
}
MethodSymbol? getBaseToStringMethod()
{
var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString);
var currentBaseType = this.BaseTypeNoUseSiteDiagnostics;
while (currentBaseType is not null)
{
foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString))
{
if (member is not MethodSymbol method)
continue;
if (method.GetLeastOverriddenMethod(null) == objectToString)
return method;
}
currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics;
}
return null;
}
}
ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters)
{
var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length);
int addedCount = 0;
foreach (ParameterSymbol param in recordParameters)
{
bool isInherited = false;
var syntax = param.GetNonNullSyntaxNode();
var targetProperty = new SignatureOnlyPropertySymbol(param.Name,
this,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
param.TypeWithAnnotations,
ImmutableArray<CustomModifier>.Empty,
isStatic: false,
ImmutableArray<PropertySymbol>.Empty);
if (!memberSignatures.TryGetValue(targetProperty, out var existingMember)
&& !fieldsByName.TryGetValue(param.Name, out existingMember))
{
existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true);
isInherited = true;
}
// There should be an error if we picked a member that is hidden
// This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630
if (existingMember is null)
{
addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics));
}
else if (existingMember is FieldSymbol { IsStatic: false } field
&& field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions))
{
Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics);
if (!isInherited || checkMemberNotHidden(field, param))
{
existingOrAddedMembers.Add(field);
}
}
else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop
&& prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions))
{
// There already exists a member corresponding to the candidate synthesized property.
if (isInherited && prop.IsAbstract)
{
addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics));
}
else if (!isInherited || checkMemberNotHidden(prop, param))
{
// Deconstruct() is specified to simply assign from this property to the corresponding out parameter.
existingOrAddedMembers.Add(prop);
}
}
else
{
diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter,
param.Locations[0],
new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)),
param.TypeWithAnnotations,
param.Name);
}
void addProperty(SynthesizedRecordPropertySymbol property)
{
existingOrAddedMembers.Add(property);
members.Add(property);
Debug.Assert(property.GetMethod is object);
Debug.Assert(property.SetMethod is object);
members.Add(property.GetMethod);
members.Add(property.SetMethod);
members.Add(property.BackingField);
builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal]));
addedCount++;
}
}
return existingOrAddedMembers.ToImmutableAndFree();
bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param)
{
if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name))
{
diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol);
return false;
}
return true;
}
}
void addObjectEquals(MethodSymbol thisEquals)
{
members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics));
}
MethodSymbol addGetHashCode(PropertySymbol? equalityContract)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.ObjectGetHashCode,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
MethodSymbol getHashCode;
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod))
{
getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics);
members.Add(getHashCode);
}
else
{
getHashCode = (MethodSymbol)existingHashCodeMethod;
if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed)
{
diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode);
}
}
return getHashCode;
}
PropertySymbol addEqualityContract()
{
Debug.Assert(isRecordClass);
var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName,
this,
ImmutableArray<ParameterSymbol>.Empty,
RefKind.None,
TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)),
ImmutableArray<CustomModifier>.Empty,
isStatic: false,
ImmutableArray<PropertySymbol>.Empty);
PropertySymbol equalityContract;
if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty))
{
equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics);
members.Add(equalityContract);
members.Add(equalityContract.GetMethod);
}
else
{
equalityContract = (PropertySymbol)existingEqualityContractProperty;
if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())
{
if (equalityContract.DeclaredAccessibility != Accessibility.Private)
{
diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract);
}
}
else if (equalityContract.DeclaredAccessibility != Accessibility.Protected)
{
diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract);
}
if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions))
{
if (!equalityContract.Type.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type);
}
}
else
{
SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics);
}
if (equalityContract.GetMethod is null)
{
diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract);
}
reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics);
}
return equalityContract;
}
MethodSymbol addThisEquals(PropertySymbol? equalityContract)
{
var targetMethod = new SignatureOnlyMethodSymbol(
WellKnownMemberNames.ObjectEquals,
this,
MethodKind.Ordinary,
Cci.CallingConvention.HasThis,
ImmutableArray<TypeParameterSymbol>.Empty,
ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(this),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
RefKind.None
)),
RefKind.None,
isInitOnly: false,
isStatic: false,
TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)),
ImmutableArray<CustomModifier>.Empty,
ImmutableArray<MethodSymbol>.Empty);
MethodSymbol thisEquals;
if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod))
{
thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics);
members.Add(thisEquals);
}
else
{
thisEquals = (MethodSymbol)existingEqualsMethod;
if (thisEquals.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals);
}
if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType())
{
diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType);
}
reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics);
}
return thisEquals;
}
void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics)
{
if (isRecordClass &&
!IsSealed &&
((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed))
{
diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol);
}
else if (symbol.IsStatic)
{
diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol);
}
}
void addBaseEquals()
{
Debug.Assert(isRecordClass);
if (!BaseTypeNoUseSiteDiagnostics.IsObjectType())
{
members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics));
}
}
void addEqualityOperators()
{
members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics));
members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics));
}
}
private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics)
{
//we're not calling the helpers on NamedTypeSymbol base, because those call
//GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow)
var hasInstanceConstructor = false;
var hasParameterlessInstanceConstructor = false;
var hasStaticConstructor = false;
// CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the
// dictionary construction process. For now, this is more encapsulated.
var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers);
foreach (var member in membersSoFar)
{
if (member.Kind == SymbolKind.Method)
{
var method = (MethodSymbol)member;
switch (method.MethodKind)
{
case MethodKind.Constructor:
// Ignore the record copy constructor
if (!IsRecord ||
!(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor))
{
hasInstanceConstructor = true;
hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0;
}
break;
case MethodKind.StaticConstructor:
hasStaticConstructor = true;
break;
}
}
//kick out early if we've seen everything we're looking for
if (hasInstanceConstructor && hasStaticConstructor)
{
break;
}
}
// NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor".
// We won't insert a parameterless constructor for a struct if there already is one.
// The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table.
if ((!hasParameterlessInstanceConstructor && this.IsStructType()) ||
(!hasInstanceConstructor && !this.IsStatic && !this.IsInterface))
{
builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ?
new SynthesizedSubmissionConstructor(this, diagnostics) :
new SynthesizedInstanceConstructor(this),
declaredMembersAndInitializers);
}
// constants don't count, since they do not exist as fields at runtime
// NOTE: even for decimal constants (which require field initializers),
// we do not create .cctor here since a static constructor implicitly created for a decimal
// should not appear in the list returned by public API like GetMembers().
if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers))
{
// Note: we don't have to put anything in the method - the binder will
// do that when processing field initializers.
builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers);
}
if (this.IsScriptClass)
{
var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics);
builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers);
var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics);
builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers);
}
static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst));
}
}
private void AddNonTypeMembers(
DeclaredMembersAndInitializersBuilder builder,
SyntaxList<MemberDeclarationSyntax> members,
BindingDiagnosticBag diagnostics)
{
if (members.Count == 0)
{
return;
}
var firstMember = members[0];
var bodyBinder = this.GetBinder(firstMember);
ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null;
ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null;
var compilation = DeclaringCompilation;
foreach (var m in members)
{
if (_lazyMembersAndInitializers != null)
{
// membersAndInitializers is already computed. no point to continue.
return;
}
bool reportMisplacedGlobalCode = !m.HasErrors;
switch (m.Kind())
{
case SyntaxKind.FieldDeclaration:
{
var fieldSyntax = (FieldDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier));
}
bool modifierErrors;
var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors);
foreach (var variable in fieldSyntax.Declaration.Variables)
{
var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0
? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics)
: new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics);
builder.NonTypeMembers.Add(fieldSymbol);
// All fields are included in the nullable context for constructors and initializers, even fields without
// initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker.
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable);
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this,
DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static),
fieldSymbol);
}
if (variable.Initializer != null)
{
if (fieldSymbol.IsStatic)
{
AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer);
}
else
{
AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer);
}
}
}
}
break;
case SyntaxKind.MethodDeclaration:
{
var methodSyntax = (MethodDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(methodSyntax.Identifier));
}
var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics);
builder.NonTypeMembers.Add(method);
}
break;
case SyntaxKind.ConstructorDeclaration:
{
var constructorSyntax = (ConstructorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(constructorSyntax.Identifier));
}
bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax);
var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics);
builder.NonTypeMembers.Add(constructor);
if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer)
{
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled);
}
}
break;
case SyntaxKind.DestructorDeclaration:
{
var destructorSyntax = (DestructorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(destructorSyntax.Identifier));
}
// CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the
// runtime won't consider it a finalizer and it will not be marked as a destructor
// when it is loaded from metadata. Perhaps we should just treat it as an Ordinary
// method in such cases?
var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics);
builder.NonTypeMembers.Add(destructor);
}
break;
case SyntaxKind.PropertyDeclaration:
{
var propertySyntax = (PropertyDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(propertySyntax.Identifier));
}
var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics);
builder.NonTypeMembers.Add(property);
AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod);
FieldSymbol backingField = property.BackingField;
// TODO: can we leave this out of the member list?
// From the 10/12/11 design notes:
// In addition, we will change autoproperties to behavior in
// a similar manner and make the autoproperty fields private.
if ((object)backingField != null)
{
builder.NonTypeMembers.Add(backingField);
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax);
var initializer = propertySyntax.Initializer;
if (initializer != null)
{
if (IsScriptClass)
{
// also gather expression-declared variables from the initializer
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers,
initializer,
this,
DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0),
backingField);
}
if (property.IsStatic)
{
AddInitializer(ref staticInitializers, backingField, initializer);
}
else
{
AddInitializer(ref instanceInitializers, backingField, initializer);
}
}
}
}
break;
case SyntaxKind.EventFieldDeclaration:
{
var eventFieldSyntax = (EventFieldDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(
ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier));
}
foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables)
{
SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics);
builder.NonTypeMembers.Add(@event);
FieldSymbol? associatedField = @event.AssociatedField;
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this,
DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0),
associatedField);
}
if ((object?)associatedField != null)
{
// NOTE: specifically don't add the associated field to the members list
// (regard it as an implementation detail).
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator);
if (declarator.Initializer != null)
{
if (associatedField.IsStatic)
{
AddInitializer(ref staticInitializers, associatedField, declarator.Initializer);
}
else
{
AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer);
}
}
}
Debug.Assert((object)@event.AddMethod != null);
Debug.Assert((object)@event.RemoveMethod != null);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod);
}
}
break;
case SyntaxKind.EventDeclaration:
{
var eventSyntax = (EventDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(eventSyntax.Identifier));
}
var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics);
builder.NonTypeMembers.Add(@event);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod);
Debug.Assert(@event.AssociatedField is null);
}
break;
case SyntaxKind.IndexerDeclaration:
{
var indexerSyntax = (IndexerDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(indexerSyntax.ThisKeyword));
}
var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics);
builder.HaveIndexers = true;
builder.NonTypeMembers.Add(indexer);
AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod);
AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod);
}
break;
case SyntaxKind.ConversionOperatorDeclaration:
{
var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(conversionOperatorSyntax.OperatorKeyword));
}
var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol(
this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics);
builder.NonTypeMembers.Add(method);
}
break;
case SyntaxKind.OperatorDeclaration:
{
var operatorSyntax = (OperatorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(operatorSyntax.OperatorKeyword));
}
var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol(
this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics);
builder.NonTypeMembers.Add(method);
}
break;
case SyntaxKind.GlobalStatement:
{
var globalStatement = ((GlobalStatementSyntax)m).Statement;
if (IsScriptClass)
{
var innerStatement = globalStatement;
// drill into any LabeledStatements
while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
{
innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
}
switch (innerStatement.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
// We shouldn't reach this place, but field declarations preceded with a label end up here.
// This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now.
var decl = (LocalDeclarationStatementSyntax)innerStatement;
foreach (var vdecl in decl.Declaration.Variables)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private,
containingFieldOpt: null);
}
break;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.LockStatement:
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers,
innerStatement,
this,
DeclarationModifiers.Private,
containingFieldOpt: null);
break;
default:
// no other statement introduces variables into the enclosing scope
break;
}
AddInitializer(ref instanceInitializers, null, globalStatement);
}
else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m))
{
diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement));
}
}
break;
default:
Debug.Assert(
SyntaxFacts.IsTypeDeclaration(m.Kind()) ||
m.Kind() is SyntaxKind.NamespaceDeclaration or
SyntaxKind.FileScopedNamespaceDeclaration or
SyntaxKind.IncompleteMember);
break;
}
}
AddInitializers(builder.InstanceInitializers, instanceInitializers);
AddInitializers(builder.StaticInitializers, staticInitializers);
}
private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt)
{
if (!(accessorOpt is null))
{
symbols.Add(accessorOpt);
}
}
internal override byte? GetLocalNullableContextValue()
{
byte? value;
if (!_flags.TryGetNullableContext(out value))
{
value = ComputeNullableContextValue();
_flags.SetNullableContext(value);
}
return value;
}
private byte? ComputeNullableContextValue()
{
var compilation = DeclaringCompilation;
if (!compilation.ShouldEmitNullableAttributes(this))
{
return null;
}
var builder = new MostCommonNullableValueBuilder();
var baseType = BaseTypeNoUseSiteDiagnostics;
if (baseType is object)
{
builder.AddValue(TypeWithAnnotations.Create(baseType));
}
foreach (var @interface in GetInterfacesToEmit())
{
builder.AddValue(TypeWithAnnotations.Create(@interface));
}
foreach (var typeParameter in TypeParameters)
{
typeParameter.GetCommonNullableValues(compilation, ref builder);
}
foreach (var member in GetMembersUnordered())
{
member.GetCommonNullableValues(compilation, ref builder);
}
// Not including lambdas or local functions.
return builder.MostCommonValue;
}
/// <summary>
/// Returns true if the overall nullable context is enabled for constructors and initializers.
/// </summary>
/// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param>
internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic)
{
var membersAndInitializers = GetMembersAndInitializers();
return useStatic ?
membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields :
membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields;
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
var compilation = DeclaringCompilation;
NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics;
if (baseType is object)
{
if (baseType.ContainsDynamic())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0));
}
if (baseType.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType));
}
if (baseType.ContainsTupleNames())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType));
}
}
if (compilation.ShouldEmitNullableAttributes(this))
{
if (ShouldEmitNullableContextValue(out byte nullableContextValue))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue));
}
if (baseType is object)
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType)));
}
}
}
#endregion
#region Extension Methods
internal bool ContainsExtensionMethods
{
get
{
if (!_lazyContainsExtensionMethods.HasValue())
{
bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods;
_lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState();
}
return _lazyContainsExtensionMethods.Value();
}
}
internal bool AnyMemberHasAttributes
{
get
{
if (!_lazyAnyMemberHasAttributes.HasValue())
{
bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes;
_lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState();
}
return _lazyAnyMemberHasAttributes.Value();
}
}
public override bool MightContainExtensionMethods
{
get
{
return this.ContainsExtensionMethods;
}
}
#endregion
public sealed override NamedTypeSymbol ConstructedFrom
{
get { return this; }
}
internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0;
internal class SynthesizedExplicitImplementations
{
public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty,
ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty);
public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods;
public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls;
private SynthesizedExplicitImplementations(
ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods,
ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls)
{
ForwardingMethods = forwardingMethods.NullToEmpty();
MethodImpls = methodImpls.NullToEmpty();
}
internal static SynthesizedExplicitImplementations Create(
ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods,
ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls)
{
if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty)
{
return Empty;
}
return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls);
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/CSharp/Portable/DocumentationComments/DocumentationCommentIDVisitor.PartVisitor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class DocumentationCommentIDVisitor
{
/// <summary>
/// A visitor that generates the part of the documentation comment after the initial type
/// and colon.
/// </summary>
private sealed class PartVisitor : CSharpSymbolVisitor<StringBuilder, object>
{
// Everyone outside this type uses this one.
internal static readonly PartVisitor Instance = new PartVisitor(inParameterOrReturnType: false);
// Select callers within this type use this one.
private static readonly PartVisitor s_parameterOrReturnTypeInstance = new PartVisitor(inParameterOrReturnType: true);
private readonly bool _inParameterOrReturnType;
private PartVisitor(bool inParameterOrReturnType)
{
_inParameterOrReturnType = inParameterOrReturnType;
}
public override object VisitArrayType(ArrayTypeSymbol symbol, StringBuilder builder)
{
Visit(symbol.ElementType, builder);
// Rank-one arrays are displayed different than rectangular arrays
if (symbol.IsSZArray)
{
builder.Append("[]");
}
else
{
builder.Append("[0:");
for (int i = 0; i < symbol.Rank - 1; i++)
{
builder.Append(",0:");
}
builder.Append(']');
}
return null;
}
public override object VisitField(FieldSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(symbol.Name);
return null;
}
private void VisitParameters(ImmutableArray<ParameterSymbol> parameters, bool isVararg, StringBuilder builder)
{
builder.Append('(');
bool needsComma = false;
foreach (var parameter in parameters)
{
if (needsComma)
{
builder.Append(',');
}
Visit(parameter, builder);
needsComma = true;
}
if (isVararg && needsComma)
{
builder.Append(',');
}
builder.Append(')');
}
public override object VisitMethod(MethodSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
if (symbol.Arity != 0)
{
builder.Append("``");
builder.Append(symbol.Arity);
}
if (symbol.Parameters.Any() || symbol.IsVararg)
{
s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, symbol.IsVararg, builder);
}
if (symbol.MethodKind == MethodKind.Conversion)
{
builder.Append('~');
s_parameterOrReturnTypeInstance.Visit(symbol.ReturnType, builder);
}
return null;
}
public override object VisitProperty(PropertySymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
if (symbol.Parameters.Any())
{
s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, false, builder);
}
return null;
}
public override object VisitEvent(EventSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
return null;
}
public override object VisitTypeParameter(TypeParameterSymbol symbol, StringBuilder builder)
{
int ordinalOffset = 0;
// Is this a type parameter on a type?
Symbol containingSymbol = symbol.ContainingSymbol;
if (containingSymbol.Kind == SymbolKind.Method)
{
builder.Append("``");
}
else
{
Debug.Assert(containingSymbol is NamedTypeSymbol);
// If the containing type is nested within other types, then we need to add their arities.
// e.g. A<T>.B<U>.M<V>(T t, U u, V v) should be M(`0, `1, ``0).
for (NamedTypeSymbol curr = containingSymbol.ContainingType; (object)curr != null; curr = curr.ContainingType)
{
ordinalOffset += curr.Arity;
}
builder.Append('`');
}
builder.Append(symbol.Ordinal + ordinalOffset);
return null;
}
public override object VisitNamedType(NamedTypeSymbol symbol, StringBuilder builder)
{
if ((object)symbol.ContainingSymbol != null && symbol.ContainingSymbol.Name.Length != 0)
{
Visit(symbol.ContainingSymbol, builder);
builder.Append('.');
}
builder.Append(symbol.Name);
if (symbol.Arity != 0)
{
// Special case: dev11 treats types instances of the declaring type in the parameter list
// (and return type, for conversions) as constructed with its own type parameters.
if (!_inParameterOrReturnType && TypeSymbol.Equals(symbol, symbol.ConstructedFrom, TypeCompareKind.ConsiderEverything2))
{
builder.Append('`');
builder.Append(symbol.Arity);
}
else
{
builder.Append('{');
bool needsComma = false;
foreach (var typeArgument in symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics)
{
if (needsComma)
{
builder.Append(',');
}
Visit(typeArgument.Type, builder);
needsComma = true;
}
builder.Append('}');
}
}
return null;
}
public override object VisitPointerType(PointerTypeSymbol symbol, StringBuilder builder)
{
Visit(symbol.PointedAtType, builder);
builder.Append('*');
return null;
}
public override object VisitNamespace(NamespaceSymbol symbol, StringBuilder builder)
{
if ((object)symbol.ContainingNamespace != null && symbol.ContainingNamespace.Name.Length != 0)
{
Visit(symbol.ContainingNamespace, builder);
builder.Append('.');
}
builder.Append(symbol.Name);
return null;
}
public override object VisitParameter(ParameterSymbol symbol, StringBuilder builder)
{
Debug.Assert(_inParameterOrReturnType);
Visit(symbol.Type, builder);
// ref and out params are suffixed with @
if (symbol.RefKind != RefKind.None)
{
builder.Append('@');
}
return null;
}
public override object VisitErrorType(ErrorTypeSymbol symbol, StringBuilder builder)
{
return VisitNamedType(symbol, builder);
}
public override object VisitDynamicType(DynamicTypeSymbol symbol, StringBuilder builder)
{
// NOTE: this is a change from dev11, which did not allow dynamic in parameter types.
// If we wanted to be really conservative, we would actually visit the symbol for
// System.Object. However, the System.Object type must always have exactly this
// doc comment ID, so the hassle seems unjustifiable.
builder.Append("System.Object");
return null;
}
private static string GetEscapedMetadataName(Symbol symbol)
{
string metadataName = symbol.MetadataName;
int colonColonIndex = metadataName.IndexOf("::", StringComparison.Ordinal);
int startIndex = colonColonIndex < 0 ? 0 : colonColonIndex + 2;
PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
pooled.Builder.Append(metadataName, startIndex, metadataName.Length - startIndex);
pooled.Builder.Replace('.', '#').Replace('<', '{').Replace('>', '}');
return pooled.ToStringAndFree();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class DocumentationCommentIDVisitor
{
/// <summary>
/// A visitor that generates the part of the documentation comment after the initial type
/// and colon.
/// </summary>
private sealed class PartVisitor : CSharpSymbolVisitor<StringBuilder, object>
{
// Everyone outside this type uses this one.
internal static readonly PartVisitor Instance = new PartVisitor(inParameterOrReturnType: false);
// Select callers within this type use this one.
private static readonly PartVisitor s_parameterOrReturnTypeInstance = new PartVisitor(inParameterOrReturnType: true);
private readonly bool _inParameterOrReturnType;
private PartVisitor(bool inParameterOrReturnType)
{
_inParameterOrReturnType = inParameterOrReturnType;
}
public override object VisitArrayType(ArrayTypeSymbol symbol, StringBuilder builder)
{
Visit(symbol.ElementType, builder);
// Rank-one arrays are displayed different than rectangular arrays
if (symbol.IsSZArray)
{
builder.Append("[]");
}
else
{
builder.Append("[0:");
for (int i = 0; i < symbol.Rank - 1; i++)
{
builder.Append(",0:");
}
builder.Append(']');
}
return null;
}
public override object VisitField(FieldSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(symbol.Name);
return null;
}
private void VisitParameters(ImmutableArray<ParameterSymbol> parameters, bool isVararg, StringBuilder builder)
{
builder.Append('(');
bool needsComma = false;
foreach (var parameter in parameters)
{
if (needsComma)
{
builder.Append(',');
}
Visit(parameter, builder);
needsComma = true;
}
if (isVararg && needsComma)
{
builder.Append(',');
}
builder.Append(')');
}
public override object VisitMethod(MethodSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
if (symbol.Arity != 0)
{
builder.Append("``");
builder.Append(symbol.Arity);
}
if (symbol.Parameters.Any() || symbol.IsVararg)
{
s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, symbol.IsVararg, builder);
}
if (symbol.MethodKind == MethodKind.Conversion)
{
builder.Append('~');
s_parameterOrReturnTypeInstance.Visit(symbol.ReturnType, builder);
}
return null;
}
public override object VisitProperty(PropertySymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
if (symbol.Parameters.Any())
{
s_parameterOrReturnTypeInstance.VisitParameters(symbol.Parameters, false, builder);
}
return null;
}
public override object VisitEvent(EventSymbol symbol, StringBuilder builder)
{
Visit(symbol.ContainingType, builder);
builder.Append('.');
builder.Append(GetEscapedMetadataName(symbol));
return null;
}
public override object VisitTypeParameter(TypeParameterSymbol symbol, StringBuilder builder)
{
int ordinalOffset = 0;
// Is this a type parameter on a type?
Symbol containingSymbol = symbol.ContainingSymbol;
if (containingSymbol.Kind == SymbolKind.Method)
{
builder.Append("``");
}
else
{
Debug.Assert(containingSymbol is NamedTypeSymbol);
// If the containing type is nested within other types, then we need to add their arities.
// e.g. A<T>.B<U>.M<V>(T t, U u, V v) should be M(`0, `1, ``0).
for (NamedTypeSymbol curr = containingSymbol.ContainingType; (object)curr != null; curr = curr.ContainingType)
{
ordinalOffset += curr.Arity;
}
builder.Append('`');
}
builder.Append(symbol.Ordinal + ordinalOffset);
return null;
}
public override object VisitNamedType(NamedTypeSymbol symbol, StringBuilder builder)
{
if ((object)symbol.ContainingSymbol != null && symbol.ContainingSymbol.Name.Length != 0)
{
Visit(symbol.ContainingSymbol, builder);
builder.Append('.');
}
builder.Append(symbol.Name);
if (symbol.Arity != 0)
{
// Special case: dev11 treats types instances of the declaring type in the parameter list
// (and return type, for conversions) as constructed with its own type parameters.
if (!_inParameterOrReturnType && TypeSymbol.Equals(symbol, symbol.ConstructedFrom, TypeCompareKind.ConsiderEverything2))
{
builder.Append('`');
builder.Append(symbol.Arity);
}
else
{
builder.Append('{');
bool needsComma = false;
foreach (var typeArgument in symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics)
{
if (needsComma)
{
builder.Append(',');
}
Visit(typeArgument.Type, builder);
needsComma = true;
}
builder.Append('}');
}
}
return null;
}
public override object VisitPointerType(PointerTypeSymbol symbol, StringBuilder builder)
{
Visit(symbol.PointedAtType, builder);
builder.Append('*');
return null;
}
public override object VisitNamespace(NamespaceSymbol symbol, StringBuilder builder)
{
if ((object)symbol.ContainingNamespace != null && symbol.ContainingNamespace.Name.Length != 0)
{
Visit(symbol.ContainingNamespace, builder);
builder.Append('.');
}
builder.Append(symbol.Name);
return null;
}
public override object VisitParameter(ParameterSymbol symbol, StringBuilder builder)
{
Debug.Assert(_inParameterOrReturnType);
Visit(symbol.Type, builder);
// ref and out params are suffixed with @
if (symbol.RefKind != RefKind.None)
{
builder.Append('@');
}
return null;
}
public override object VisitErrorType(ErrorTypeSymbol symbol, StringBuilder builder)
{
return VisitNamedType(symbol, builder);
}
public override object VisitDynamicType(DynamicTypeSymbol symbol, StringBuilder builder)
{
// NOTE: this is a change from dev11, which did not allow dynamic in parameter types.
// If we wanted to be really conservative, we would actually visit the symbol for
// System.Object. However, the System.Object type must always have exactly this
// doc comment ID, so the hassle seems unjustifiable.
builder.Append("System.Object");
return null;
}
private static string GetEscapedMetadataName(Symbol symbol)
{
string metadataName = symbol.MetadataName;
int colonColonIndex = metadataName.IndexOf("::", StringComparison.Ordinal);
int startIndex = colonColonIndex < 0 ? 0 : colonColonIndex + 2;
PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
pooled.Builder.Append(metadataName, startIndex, metadataName.Length - startIndex);
pooled.Builder.Replace('.', '#').Replace('<', '{').Replace('>', '}');
return pooled.ToStringAndFree();
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/VisualStudio/LiveShare/Impl/Client/StringConstants.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client
{
internal class StringConstants
{
public const string BaseRemoteAssemblyTitle = "Base Remote Language Service";
// The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client
public const string RoslynContractName = "Roslyn";
// The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client
public const string RoslynLspSdkContractName = "RoslynLSPSDK";
// LSP server provider names.
public const string RoslynProviderName = "Roslyn";
public const string CSharpProviderName = "RoslynCSharp";
public const string VisualBasicProviderName = "RoslynVisualBasic";
public const string TypeScriptProviderName = "RoslynTypeScript";
public const string AnyProviderName = "any";
public const string TypeScriptLanguageName = "TypeScript";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client
{
internal class StringConstants
{
public const string BaseRemoteAssemblyTitle = "Base Remote Language Service";
// The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client
public const string RoslynContractName = "Roslyn";
// The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client
public const string RoslynLspSdkContractName = "RoslynLSPSDK";
// LSP server provider names.
public const string RoslynProviderName = "Roslyn";
public const string CSharpProviderName = "RoslynCSharp";
public const string VisualBasicProviderName = "RoslynVisualBasic";
public const string TypeScriptProviderName = "RoslynTypeScript";
public const string AnyProviderName = "any";
public const string TypeScriptLanguageName = "TypeScript";
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Persistence;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.VisualStudio.Threading;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.Workspace)]
public class SolutionTests : TestBase
{
#nullable enable
private static readonly MetadataReference s_mscorlib = TestMetadata.Net451.mscorlib;
private static readonly DocumentId s_unrelatedDocumentId = DocumentId.CreateNewId(ProjectId.CreateNewId());
private static Workspace CreateWorkspaceWithProjectAndDocuments()
{
var projectId = ProjectId.CreateNewId();
var workspace = CreateWorkspace();
Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp)
.AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }")
.AddAdditionalDocument(DocumentId.CreateNewId(projectId), "add.txt", "text")
.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"), filePath: "/a/b")));
return workspace;
}
private static IEnumerable<T> EmptyEnumerable<T>()
{
yield break;
}
// Returns an enumerable that can only be enumerated once.
private static IEnumerable<T> OnceEnumerable<T>(params T[] items)
=> OnceEnumerableImpl(new StrongBox<int>(), items);
private static IEnumerable<T> OnceEnumerableImpl<T>(StrongBox<int> counter, T[] items)
{
Assert.Equal(0, counter.Value);
counter.Value++;
foreach (var item in items)
{
yield return item;
}
}
[Fact]
public void RemoveDocument_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveDocument(null!));
Assert.Throws<InvalidOperationException>(() => solution.RemoveDocument(s_unrelatedDocumentId));
}
[Fact]
public void RemoveDocuments_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(default));
Assert.Throws<InvalidOperationException>(() => solution.RemoveDocuments(ImmutableArray.Create(s_unrelatedDocumentId)));
Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(ImmutableArray.Create((DocumentId)null!)));
}
[Fact]
public void RemoveAdditionalDocument_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocument(null!));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocument(s_unrelatedDocumentId));
}
[Fact]
public void RemoveAdditionalDocuments_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(default));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create(s_unrelatedDocumentId)));
Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create((DocumentId)null!)));
}
[Fact]
public void RemoveAnalyzerConfigDocument_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocument(null!));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocument(s_unrelatedDocumentId));
}
[Fact]
public void RemoveAnalyzerConfigDocuments_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(default));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create(s_unrelatedDocumentId)));
Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create((DocumentId)null!)));
}
[Fact]
public void WithDocumentName()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var name = "new name";
var newSolution1 = solution.WithDocumentName(documentId, name);
Assert.Equal(name, newSolution1.GetDocument(documentId)!.Name);
var newSolution2 = newSolution1.WithDocumentName(documentId, name);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(documentId, name: null!));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(null!, name));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentName(s_unrelatedDocumentId, name));
}
[Fact]
public void WithDocumentFolders()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var folders = new[] { "folder1", "folder2" };
var newSolution1 = solution.WithDocumentFolders(documentId, folders);
Assert.Equal(folders, newSolution1.GetDocument(documentId)!.Folders);
var newSolution2 = newSolution1.WithDocumentFolders(documentId, folders);
Assert.Same(newSolution2, newSolution1);
// empty:
var newSolution3 = solution.WithDocumentFolders(documentId, new string[0]);
Assert.Equal(new string[0], newSolution3.GetDocument(documentId)!.Folders);
var newSolution4 = solution.WithDocumentFolders(documentId, ImmutableArray<string>.Empty);
Assert.Same(newSolution3, newSolution4);
var newSolution5 = solution.WithDocumentFolders(documentId, null);
Assert.Same(newSolution3, newSolution5);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(documentId, folders: new string[] { null! }));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(null!, folders));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFolders(s_unrelatedDocumentId, folders));
}
[Fact]
[WorkItem(34837, "https://github.com/dotnet/roslyn/issues/34837")]
[WorkItem(37125, "https://github.com/dotnet/roslyn/issues/37125")]
public void WithDocumentFilePath()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var path = "new path";
var newSolution1 = solution.WithDocumentFilePath(documentId, path);
Assert.Equal(path, newSolution1.GetDocument(documentId)!.FilePath);
AssertEx.Equal(new[] { documentId }, newSolution1.GetDocumentIdsWithFilePath(path));
var newSolution2 = newSolution1.WithDocumentFilePath(documentId, path);
Assert.Same(newSolution1, newSolution2);
// empty path (TODO https://github.com/dotnet/roslyn/issues/37125):
var newSolution3 = solution.WithDocumentFilePath(documentId, "");
Assert.Equal("", newSolution3.GetDocument(documentId)!.FilePath);
Assert.Empty(newSolution3.GetDocumentIdsWithFilePath(""));
// TODO: https://github.com/dotnet/roslyn/issues/37125
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(documentId, filePath: null!));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(null!, path));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFilePath(s_unrelatedDocumentId, path));
}
[Fact]
public void WithSourceCodeKind()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
Assert.Same(solution, solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Regular));
var newSolution1 = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Script);
Assert.Equal(SourceCodeKind.Script, newSolution1.GetDocument(documentId)!.SourceCodeKind);
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSourceCodeKind(documentId, (SourceCodeKind)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSourceCodeKind(null!, SourceCodeKind.Script));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSourceCodeKind(s_unrelatedDocumentId, SourceCodeKind.Script));
}
[Fact, Obsolete]
public void WithSourceCodeKind_Obsolete()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var newSolution = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Interactive);
Assert.Equal(SourceCodeKind.Script, newSolution.GetDocument(documentId)!.SourceCodeKind);
}
[Fact]
public void WithDocumentSyntaxRoot()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var root = CS.SyntaxFactory.ParseSyntaxTree("class NewClass {}").GetRoot();
var newSolution1 = solution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetSyntaxRoot(out var actualRoot));
Assert.Equal(root.ToString(), actualRoot!.ToString());
// the actual root has a new parent SyntaxTree:
Assert.NotSame(root, actualRoot);
var newSolution2 = newSolution1.WithDocumentSyntaxRoot(documentId, actualRoot);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSyntaxRoot(documentId, root, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSyntaxRoot(null!, root));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSyntaxRoot(s_unrelatedDocumentId, root));
}
[Fact]
[WorkItem(37125, "https://github.com/dotnet/roslyn/issues/41940")]
public async Task WithDocumentSyntaxRoot_AnalyzerConfigWithoutFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }")
.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"));
var project = solution.GetProject(projectId)!;
var compilation = (await project.GetCompilationAsync())!;
var tree = compilation.SyntaxTrees.Single();
var provider = compilation.Options.SyntaxTreeOptionsProvider!;
Assert.Throws<ArgumentException>(() => provider.TryGetDiagnosticValue(tree, "CA1234", CancellationToken.None, out _));
}
[Fact]
public void WithDocumentText_SourceText()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, text, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithDocumentText_TextAndVersion()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
var newSolution1 = solution.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
Assert.True(newSolution1.GetDocument(documentId)!.TryGetTextVersion(out var actualVersion));
Assert.Same(textAndVersion.Text, actualText);
Assert.Equal(textAndVersion.Version, actualVersion);
var newSolution2 = newSolution1.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, textAndVersion, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithDocumentText_MultipleDocuments()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
// documents not in solution are skipped: https://github.com/dotnet/roslyn/issues/42029
Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { null! }, text));
Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { s_unrelatedDocumentId }, text));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId[])null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(new[] { documentId }, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(new[] { documentId }, text, (PreservationMode)(-1)));
}
[Fact]
public void WithAdditionalDocumentText_SourceText()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AdditionalDocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, text, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAdditionalDocumentText_TextAndVersion()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AdditionalDocumentIds.Single();
var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
var newSolution1 = solution.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText));
Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetTextVersion(out var actualVersion));
Assert.Same(textAndVersion.Text, actualText);
Assert.Equal(textAndVersion.Version, actualVersion);
var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, textAndVersion, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAnalyzerConfigDocumentText_SourceText()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, text, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAnalyzerConfigDocumentText_TextAndVersion()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single();
var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText));
Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetTextVersion(out var actualVersion));
Assert.Same(textAndVersion.Text, actualText);
Assert.Equal(textAndVersion.Version, actualVersion);
var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithDocumentTextLoader()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var loader = new TestTextLoader("new text");
var newSolution1 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.Equal("new text", newSolution1.GetDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString());
// Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028
var newSolution2 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.NotSame(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentTextLoader(documentId, loader, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAdditionalDocumentTextLoader()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AdditionalDocumentIds.Single();
var loader = new TestTextLoader("new text");
var newSolution1 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.Equal("new text", newSolution1.GetAdditionalDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString());
// Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028
var newSolution2 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.NotSame(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentTextLoader(documentId, loader, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAnalyzerConfigDocumentTextLoader()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single();
var loader = new TestTextLoader("new text");
var newSolution1 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.Equal("new text", newSolution1.GetAnalyzerConfigDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString());
// Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028
var newSolution2 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.NotSame(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithProjectAssemblyName()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var assemblyName = "\0<>a/b/*.dll";
var newSolution = solution.WithProjectAssemblyName(projectId, assemblyName);
Assert.Equal(assemblyName, newSolution.GetProject(projectId)!.AssemblyName);
Assert.Same(newSolution, newSolution.WithProjectAssemblyName(projectId, assemblyName));
Assert.Throws<ArgumentNullException>("assemblyName", () => solution.WithProjectAssemblyName(projectId, null!));
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAssemblyName(null!, "x.dll"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectAssemblyName(ProjectId.CreateNewId(), "x.dll"));
}
[Fact]
public void WithProjectOutputFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.dll";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectOutputFilePath(projectId, value),
s => s.GetProject(projectId)!.OutputFilePath,
(string?)path,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputFilePath(null!, "x.dll"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputFilePath(ProjectId.CreateNewId(), "x.dll"));
}
[Fact]
public void WithProjectOutputRefFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.dll";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectOutputRefFilePath(projectId, value),
s => s.GetProject(projectId)!.OutputRefFilePath,
(string?)path,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputRefFilePath(null!, "x.dll"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputRefFilePath(ProjectId.CreateNewId(), "x.dll"));
}
[Fact]
public void WithProjectCompilationOutputInfo()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.dll";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectCompilationOutputInfo(projectId, value),
s => s.GetProject(projectId)!.CompilationOutputInfo,
new CompilationOutputInfo(path),
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOutputInfo(null!, new CompilationOutputInfo("x.dll")));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOutputInfo(ProjectId.CreateNewId(), new CompilationOutputInfo("x.dll")));
}
[Fact]
public void WithProjectDefaultNamespace()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var defaultNamespace = "\0<>a/b/*";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectDefaultNamespace(projectId, value),
s => s.GetProject(projectId)!.DefaultNamespace,
(string?)defaultNamespace,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectDefaultNamespace(null!, "x"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectDefaultNamespace(ProjectId.CreateNewId(), "x"));
}
[Fact]
public void WithProjectName()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var projectName = "\0<>a/b/*";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectName(projectId, value),
s => s.GetProject(projectId)!.Name,
projectName,
defaultThrows: true);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectName(null!, "x"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectName(ProjectId.CreateNewId(), "x"));
}
[Fact]
public void WithProjectFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.csproj";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectFilePath(projectId, value),
s => s.GetProject(projectId)!.FilePath,
(string?)path,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectFilePath(null!, "x"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectFilePath(ProjectId.CreateNewId(), "x"));
}
[Fact]
public void WithProjectCompilationOptionsExceptionHandling()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
var options = new CSharpCompilationOptions(OutputKind.NetModule);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOptions(null!, options));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOptions(ProjectId.CreateNewId(), options));
}
[Theory]
[CombinatorialData]
public void WithProjectCompilationOptionsReplacesSyntaxTreeOptionProvider([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName)
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", languageName);
// We always have a non-null SyntaxTreeOptionsProvider for C# and VB projects
var originalSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider;
Assert.NotNull(originalSyntaxTreeOptionsProvider);
var defaultOptions = solution.Projects.Single().LanguageServices.GetRequiredService<ICompilationFactoryService>().GetDefaultCompilationOptions();
Assert.Null(defaultOptions.SyntaxTreeOptionsProvider);
solution = solution.WithProjectCompilationOptions(projectId, defaultOptions);
// The CompilationOptions we replaced with didn't have a SyntaxTreeOptionsProvider, but we would have placed it
// back. The SyntaxTreeOptionsProvider should behave the same as the prior one and thus should be equal.
var newSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider;
Assert.NotNull(newSyntaxTreeOptionsProvider);
Assert.Equal(originalSyntaxTreeOptionsProvider, newSyntaxTreeOptionsProvider);
}
[Fact]
public void WithProjectParseOptions()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
var options = new CSharpParseOptions(CS.LanguageVersion.CSharp1);
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectParseOptions(projectId, value),
s => s.GetProject(projectId)!.ParseOptions!,
(ParseOptions)options,
defaultThrows: true);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectParseOptions(null!, options));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectParseOptions(ProjectId.CreateNewId(), options));
}
[Fact]
public void WithProjectReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var projectId2 = ProjectId.CreateNewId();
solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp);
var projectRef = new ProjectReference(projectId2);
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithProjectReferences(projectId, value),
opt => opt.GetProject(projectId)!.AllProjectReferences,
projectRef,
allowDuplicates: false);
var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(
new ProjectReference(projectId2),
new ProjectReference(projectId2, ImmutableArray.Create("alias")),
new ProjectReference(projectId2, embedInteropTypes: true));
var solution2 = solution.WithProjectReferences(projectId, projectRefs);
Assert.Same(projectRefs, solution2.GetProject(projectId)!.AllProjectReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectReferences(null!, new[] { projectRef }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(ProjectId.CreateNewId(), new[] { projectRef }));
// cycles:
Assert.Throws<InvalidOperationException>(() => solution2.WithProjectReferences(projectId2, new[] { new ProjectReference(projectId) }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId, new[] { new ProjectReference(projectId) }));
}
[Fact]
[WorkItem(42406, "https://github.com/dotnet/roslyn/issues/42406")]
public void WithProjectReferences_ProjectNotInSolution()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var externalProjectRef = new ProjectReference(ProjectId.CreateNewId());
var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(externalProjectRef);
var newSolution1 = solution.WithProjectReferences(projectId, projectRefs);
Assert.Same(projectRefs, newSolution1.GetProject(projectId)!.AllProjectReferences);
// project reference is not included:
Assert.Empty(newSolution1.GetProject(projectId)!.ProjectReferences);
}
[Fact]
public void AddProjectReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
solution = solution
.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp)
.AddProject(projectId3, "proj3", "proj3.dll", LanguageNames.CSharp);
var projectRef2 = new ProjectReference(projectId2);
var projectRef3 = new ProjectReference(projectId3);
var externalProjectRef = new ProjectReference(ProjectId.CreateNewId());
solution = solution.AddProjectReference(projectId3, projectRef2);
var solution2 = solution.AddProjectReferences(projectId, EmptyEnumerable<ProjectReference>());
Assert.Same(solution, solution2);
var e = OnceEnumerable(projectRef2, externalProjectRef);
var solution3 = solution.AddProjectReferences(projectId, e);
AssertEx.Equal(new[] { projectRef2 }, solution3.GetProject(projectId)!.ProjectReferences);
AssertEx.Equal(new[] { projectRef2, externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.AddProjectReferences(null!, new[] { projectRef2 }));
Assert.Throws<ArgumentNullException>("projectReferences", () => solution.AddProjectReferences(projectId, null!));
Assert.Throws<ArgumentNullException>("projectReferences[0]", () => solution.AddProjectReferences(projectId, new ProjectReference[] { null! }));
Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { projectRef2, projectRef2 }));
Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { new ProjectReference(projectId2), new ProjectReference(projectId2) }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId3, new[] { projectRef2 }));
// cycles:
Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId2, new[] { projectRef3 }));
Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId, new[] { new ProjectReference(projectId) }));
}
[Fact]
public void RemoveProjectReference()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var projectId2 = ProjectId.CreateNewId();
solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp);
var projectRef2 = new ProjectReference(projectId2);
var externalProjectRef = new ProjectReference(ProjectId.CreateNewId());
solution = solution.WithProjectReferences(projectId, new[] { projectRef2, externalProjectRef });
// remove reference to a project that's not part of the solution:
var solution2 = solution.RemoveProjectReference(projectId, externalProjectRef);
AssertEx.Equal(new[] { projectRef2 }, solution2.GetProject(projectId)!.AllProjectReferences);
// remove reference to a project that's part of the solution:
var solution3 = solution.RemoveProjectReference(projectId, projectRef2);
AssertEx.Equal(new[] { externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences);
var solution4 = solution3.RemoveProjectReference(projectId, externalProjectRef);
Assert.Empty(solution4.GetProject(projectId)!.AllProjectReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveProjectReference(null!, projectRef2));
Assert.Throws<ArgumentNullException>("projectReference", () => solution.RemoveProjectReference(projectId, null!));
// removing a reference that's not in the list:
Assert.Throws<ArgumentException>("projectReference", () => solution.RemoveProjectReference(projectId, new ProjectReference(ProjectId.CreateNewId())));
// project not in solution:
Assert.Throws<InvalidOperationException>(() => solution.RemoveProjectReference(ProjectId.CreateNewId(), projectRef2));
}
[Fact]
public void ProjectReferences_Submissions()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId0 = ProjectId.CreateNewId();
var submissionId1 = ProjectId.CreateNewId();
var submissionId2 = ProjectId.CreateNewId();
var submissionId3 = ProjectId.CreateNewId();
solution = solution
.AddProject(projectId0, "non-submission", "non-submission.dll", LanguageNames.CSharp)
.AddProject(ProjectInfo.Create(submissionId1, VersionStamp.Default, name: "submission1", assemblyName: "submission1.dll", LanguageNames.CSharp, isSubmission: true))
.AddProject(ProjectInfo.Create(submissionId2, VersionStamp.Default, name: "submission2", assemblyName: "submission2.dll", LanguageNames.CSharp, isSubmission: true))
.AddProject(ProjectInfo.Create(submissionId3, VersionStamp.Default, name: "submission3", assemblyName: "submission3.dll", LanguageNames.CSharp, isSubmission: true))
.AddProjectReference(submissionId2, new ProjectReference(submissionId1))
.WithProjectReferences(submissionId2, new[] { new ProjectReference(submissionId1) });
// submission may be referenced from multiple submissions (forming a tree):
_ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) });
_ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) });
// submission may reference a non-submission project:
_ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) });
_ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) });
// submission can't reference multiple submissions:
Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(submissionId2, new[] { new ProjectReference(submissionId3) }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(submissionId1, new[] { new ProjectReference(submissionId2), new ProjectReference(submissionId3) }));
// non-submission project can't reference a submission:
Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) }));
}
[Fact]
public void WithProjectMetadataReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var metadataRef = (MetadataReference)new TestMetadataReference();
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithProjectMetadataReferences(projectId, value),
opt => opt.GetProject(projectId)!.MetadataReferences,
metadataRef,
allowDuplicates: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectMetadataReferences(null!, new[] { metadataRef }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectMetadataReferences(ProjectId.CreateNewId(), new[] { metadataRef }));
}
[Fact]
public void AddMetadataReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var solution2 = solution.AddMetadataReferences(projectId, EmptyEnumerable<MetadataReference>());
Assert.Same(solution, solution2);
var metadataRef1 = new TestMetadataReference();
var metadataRef2 = new TestMetadataReference();
var solution3 = solution.AddMetadataReferences(projectId, OnceEnumerable(metadataRef1, metadataRef2));
AssertEx.Equal(new[] { metadataRef1, metadataRef2 }, solution3.GetProject(projectId)!.MetadataReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.AddMetadataReferences(null!, new[] { metadataRef1 }));
Assert.Throws<ArgumentNullException>("metadataReferences", () => solution.AddMetadataReferences(projectId, null!));
Assert.Throws<ArgumentNullException>("metadataReferences[0]", () => solution.AddMetadataReferences(projectId, new MetadataReference[] { null! }));
Assert.Throws<ArgumentException>("metadataReferences[1]", () => solution.AddMetadataReferences(projectId, new[] { metadataRef1, metadataRef1 }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution3.AddMetadataReferences(projectId, new[] { metadataRef1 }));
}
[Fact]
public void RemoveMetadataReference()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var metadataRef1 = new TestMetadataReference();
var metadataRef2 = new TestMetadataReference();
solution = solution.WithProjectMetadataReferences(projectId, new[] { metadataRef1, metadataRef2 });
var solution2 = solution.RemoveMetadataReference(projectId, metadataRef1);
AssertEx.Equal(new[] { metadataRef2 }, solution2.GetProject(projectId)!.MetadataReferences);
var solution3 = solution2.RemoveMetadataReference(projectId, metadataRef2);
Assert.Empty(solution3.GetProject(projectId)!.MetadataReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveMetadataReference(null!, metadataRef1));
Assert.Throws<ArgumentNullException>("metadataReference", () => solution.RemoveMetadataReference(projectId, null!));
// removing a reference that's not in the list:
Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(projectId, new TestMetadataReference()));
// project not in solution:
Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(ProjectId.CreateNewId(), metadataRef1));
}
[Fact]
public void WithProjectAnalyzerReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var analyzerRef = (AnalyzerReference)new TestAnalyzerReference();
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithProjectAnalyzerReferences(projectId, value),
opt => opt.GetProject(projectId)!.AnalyzerReferences,
analyzerRef,
allowDuplicates: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAnalyzerReferences(null!, new[] { analyzerRef }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectAnalyzerReferences(ProjectId.CreateNewId(), new[] { analyzerRef }));
}
[Fact]
public void AddAnalyzerReferences_Project()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var solution2 = solution.AddAnalyzerReferences(projectId, EmptyEnumerable<AnalyzerReference>());
Assert.Same(solution, solution2);
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
var solution3 = solution.AddAnalyzerReferences(projectId, OnceEnumerable(analyzerRef1, analyzerRef2));
AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.GetProject(projectId)!.AnalyzerReferences);
var solution4 = solution3.AddAnalyzerReferences(projectId, new AnalyzerReference[0]);
Assert.Same(solution, solution2);
Assert.Throws<ArgumentNullException>("projectId", () => solution.AddAnalyzerReferences(null!, new[] { analyzerRef1 }));
Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(projectId, null!));
Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(projectId, new AnalyzerReference[] { null! }));
Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef1 }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(projectId, new[] { analyzerRef1 }));
}
[Fact]
public void RemoveAnalyzerReference_Project()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
solution = solution.WithProjectAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef2 });
var solution2 = solution.RemoveAnalyzerReference(projectId, analyzerRef1);
AssertEx.Equal(new[] { analyzerRef2 }, solution2.GetProject(projectId)!.AnalyzerReferences);
var solution3 = solution2.RemoveAnalyzerReference(projectId, analyzerRef2);
Assert.Empty(solution3.GetProject(projectId)!.AnalyzerReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveAnalyzerReference(null!, analyzerRef1));
Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(projectId, null!));
// removing a reference that's not in the list:
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(projectId, new TestAnalyzerReference()));
// project not in solution:
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(ProjectId.CreateNewId(), analyzerRef1));
}
[Fact]
public void WithAnalyzerReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var analyzerRef = (AnalyzerReference)new TestAnalyzerReference();
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithAnalyzerReferences(value),
opt => opt.AnalyzerReferences,
analyzerRef,
allowDuplicates: false);
}
[Fact]
public void AddAnalyzerReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var solution2 = solution.AddAnalyzerReferences(EmptyEnumerable<AnalyzerReference>());
Assert.Same(solution, solution2);
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
var solution3 = solution.AddAnalyzerReferences(OnceEnumerable(analyzerRef1, analyzerRef2));
AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.AnalyzerReferences);
var solution4 = solution3.AddAnalyzerReferences(new AnalyzerReference[0]);
Assert.Same(solution, solution2);
Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(null!));
Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(new AnalyzerReference[] { null! }));
Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(new[] { analyzerRef1, analyzerRef1 }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(new[] { analyzerRef1 }));
}
[Fact]
public void RemoveAnalyzerReference()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
solution = solution.WithAnalyzerReferences(new[] { analyzerRef1, analyzerRef2 });
var solution2 = solution.RemoveAnalyzerReference(analyzerRef1);
AssertEx.Equal(new[] { analyzerRef2 }, solution2.AnalyzerReferences);
var solution3 = solution2.RemoveAnalyzerReference(analyzerRef2);
Assert.Empty(solution3.AnalyzerReferences);
Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(null!));
// removing a reference that's not in the list:
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(new TestAnalyzerReference()));
}
#nullable disable
[Fact]
public void TestAddProject()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
solution = solution.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp);
Assert.True(solution.ProjectIds.Any(), "Solution was expected to have projects");
Assert.NotNull(pid);
var project = solution.GetProject(pid);
Assert.False(project.HasDocuments);
}
[Fact]
public void TestUpdateAssemblyName()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
solution = solution.WithProjectAssemblyName(project1, "bar");
var project = solution.GetProject(project1);
Assert.Equal("bar", project.AssemblyName);
}
[Fact]
[WorkItem(543964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543964")]
public void MultipleProjectsWithSameDisplayName()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
var project2 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "name", "assemblyName", LanguageNames.CSharp);
solution = solution.AddProject(project2, "name", "assemblyName", LanguageNames.CSharp);
Assert.Equal(2, solution.GetProjectsByName("name").Count());
}
[Fact]
public async Task TestAddFirstDocumentAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", "public class Goo { }");
// verify project & document
Assert.NotNull(pid);
var project = solution.GetProject(pid);
Assert.NotNull(project);
Assert.True(solution.ContainsProject(pid), "Solution was expected to have project " + pid);
Assert.True(project.HasDocuments, "Project was expected to have documents");
Assert.Equal(project, solution.GetProject(pid));
Assert.NotNull(did);
var document = solution.GetDocument(did);
Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did);
Assert.Equal(document, project.GetDocument(did));
Assert.Equal(document, solution.GetDocument(did));
var semantics = await document.GetSemanticModelAsync();
Assert.NotNull(semantics);
await ValidateSolutionAndCompilationsAsync(solution);
var pid2 = solution.Projects.Single().Id;
var did2 = DocumentId.CreateNewId(pid2);
solution = solution.AddDocument(did2, "bar.cs", "public class Bar { }");
// verify project & document
var project2 = solution.GetProject(pid2);
Assert.NotNull(project2);
Assert.NotNull(did2);
var document2 = solution.GetDocument(did2);
Assert.True(project2.ContainsDocument(did2), "Project was expected to have document " + did2);
Assert.Equal(document2, project2.GetDocument(did2));
Assert.Equal(document2, solution.GetDocument(did2));
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task AddTwoDocumentsForSingleProject()
{
var projectId = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
var project = Assert.Single(solution.Projects);
var document1 = project.GetDocument(documentInfo1.Id);
var document2 = project.GetDocument(documentInfo2.Id);
Assert.NotSame(document1, document2);
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task AddTwoDocumentsForTwoProjects()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
var project1 = solution.GetProject(projectId1);
var project2 = solution.GetProject(projectId2);
var document1 = project1.GetDocument(documentInfo1.Id);
var document2 = project2.GetDocument(documentInfo2.Id);
Assert.NotSame(document1, document2);
Assert.NotSame(document1.Project, document2.Project);
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public void AddTwoDocumentsWithMissingProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs");
// We're only adding the first project, but not the second one
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp);
Assert.ThrowsAny<InvalidOperationException>(() => solution.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)));
}
[Fact]
public void RemoveZeroDocuments()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Same(solution, solution.RemoveDocuments(ImmutableArray<DocumentId>.Empty));
}
[Fact]
public async Task RemoveTwoDocuments()
{
var projectId = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "project1", "project1.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id));
var finalProject = solution.Projects.Single();
Assert.Empty(finalProject.Documents);
Assert.Empty((await finalProject.GetCompilationAsync()).SyntaxTrees);
}
[Fact]
public void RemoveTwoDocumentsFromDifferentProjects()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
Assert.All(solution.Projects, p => Assert.Single(p.Documents));
solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id));
Assert.All(solution.Projects, p => Assert.Empty(p.Documents));
}
[Fact]
public void RemoveDocumentFromUnrelatedProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddDocument(documentInfo1);
// This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveDocument
// API due to https://github.com/dotnet/roslyn/issues/41211.
Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveDocuments(ImmutableArray.Create(documentInfo1.Id)));
}
[Fact]
public void RemoveAdditionalDocumentFromUnrelatedProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.txt");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddAdditionalDocument(documentInfo1);
// This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument
// API due to https://github.com/dotnet/roslyn/issues/41211.
Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAdditionalDocuments(ImmutableArray.Create(documentInfo1.Id)));
}
[Fact]
public void RemoveAnalyzerConfigDocumentFromUnrelatedProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), ".editorconfig");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1));
// This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument
// API due to https://github.com/dotnet/roslyn/issues/41211.
Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1.Id)));
}
[Fact]
public async Task TestOneCSharpProjectAsync()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject("goo", "goo.dll", LanguageNames.CSharp)
.AddMetadataReference(s_mscorlib)
.AddDocument("goo.cs", "public class Goo { }")
.Project.Solution;
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task TestTwoCSharpProjectsAsync()
{
using var workspace = CreateWorkspace();
var pm1 = ProjectId.CreateNewId();
var pm2 = ProjectId.CreateNewId();
var doc1 = DocumentId.CreateNewId(pm1);
var doc2 = DocumentId.CreateNewId(pm2);
var solution = workspace.CurrentSolution
.AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp)
.AddProject(pm2, "bar", "bar.dll", LanguageNames.CSharp)
.AddProjectReference(pm2, new ProjectReference(pm1))
.AddDocument(doc1, "goo.cs", "public class Goo { }")
.AddDocument(doc2, "bar.cs", "public class Bar : Goo { }");
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task TestCrossLanguageProjectsAsync()
{
var pm1 = ProjectId.CreateNewId();
var pm2 = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp)
.AddMetadataReference(pm1, s_mscorlib)
.AddProject(pm2, "bar", "bar.dll", LanguageNames.VisualBasic)
.AddMetadataReference(pm2, s_mscorlib)
.AddProjectReference(pm2, new ProjectReference(pm1))
.AddDocument(DocumentId.CreateNewId(pm1), "goo.cs", "public class X { }")
.AddDocument(DocumentId.CreateNewId(pm2), "bar.vb", "Public Class Y\r\nInherits X\r\nEnd Class");
await ValidateSolutionAndCompilationsAsync(solution);
}
private static async Task ValidateSolutionAndCompilationsAsync(Solution solution)
{
foreach (var project in solution.Projects)
{
Assert.True(solution.ContainsProject(project.Id), "Solution was expected to have project " + project.Id);
Assert.Equal(project, solution.GetProject(project.Id));
// these won't always be unique in real-world but should be for these tests
Assert.Equal(project, solution.GetProjectsByName(project.Name).FirstOrDefault());
var compilation = await project.GetCompilationAsync();
Assert.NotNull(compilation);
// check that the options are the same
Assert.Equal(project.CompilationOptions, compilation.Options);
// check that all known metadata references are present in the compilation
foreach (var meta in project.MetadataReferences)
{
Assert.True(compilation.References.Contains(meta), "Compilation references were expected to contain " + meta);
}
// check that all project-to-project reference metadata is present in the compilation
foreach (var referenced in project.ProjectReferences)
{
if (solution.ContainsProject(referenced.ProjectId))
{
var referencedMetadata = await solution.State.GetMetadataReferenceAsync(referenced, solution.GetProjectState(project.Id), CancellationToken.None);
Assert.NotNull(referencedMetadata);
if (referencedMetadata is CompilationReference compilationReference)
{
compilation.References.Single(r =>
{
var cr = r as CompilationReference;
return cr != null && cr.Compilation == compilationReference.Compilation;
});
}
}
}
// check that the syntax trees are the same
var docs = project.Documents.ToList();
var trees = compilation.SyntaxTrees.ToList();
Assert.Equal(docs.Count, trees.Count);
foreach (var doc in docs)
{
Assert.True(trees.Contains(await doc.GetSyntaxTreeAsync()), "trees list was expected to contain the syntax tree of doc");
}
}
}
#if false
[Fact(Skip = "641963")]
public void TestDeepProjectReferenceTree()
{
int projectCount = 5;
var solution = CreateSolutionWithProjectDependencyChain(projectCount);
ProjectId[] projectIds = solution.ProjectIds.ToArray();
Compilation compilation;
for (int i = 0; i < projectCount; i++)
{
Assert.False(solution.GetProject(projectIds[i]).TryGetCompilation(out compilation));
}
var top = solution.GetCompilationAsync(projectIds.Last(), CancellationToken.None).Result;
var partialSolution = solution.GetPartialSolution();
for (int i = 0; i < projectCount; i++)
{
// While holding a compilation, we also hold its references, plus one further level
// of references alive. However, the references are only partial Declaration
// compilations
var isPartialAvailable = i >= projectCount - 3;
var isFinalAvailable = i == projectCount - 1;
var projectId = projectIds[i];
Assert.Equal(isFinalAvailable, solution.GetProject(projectId).TryGetCompilation(out compilation));
Assert.Equal(isPartialAvailable, partialSolution.ProjectIds.Contains(projectId) && partialSolution.GetProject(projectId).TryGetCompilation(out compilation));
}
}
#endif
[WorkItem(636431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636431")]
[Fact]
public async Task TestProjectDependencyLoadingAsync()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var solution = workspace.CurrentSolution;
var projectIds = Enumerable.Range(0, 5).Select(i => ProjectId.CreateNewId()).ToArray();
for (var i = 0; i < projectIds.Length; i++)
{
solution = solution.AddProject(projectIds[i], i.ToString(), i.ToString(), LanguageNames.CSharp);
if (i >= 1)
{
solution = solution.AddProjectReference(projectIds[i], new ProjectReference(projectIds[i - 1]));
}
}
await solution.GetProject(projectIds[0]).GetCompilationAsync(CancellationToken.None);
await solution.GetProject(projectIds[2]).GetCompilationAsync(CancellationToken.None);
}
[Fact]
public async Task TestAddMetadataReferencesAsync()
{
var mefReference = TestMetadata.Net451.SystemCore;
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
solution = solution.AddMetadataReference(project1, s_mscorlib);
solution = solution.AddMetadataReference(project1, mefReference);
var assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference);
var namespacesAndTypes = assemblyReference.GlobalNamespace.GetAllNamespacesAndTypes(CancellationToken.None);
var foundSymbol = from symbol in namespacesAndTypes
where symbol.Name.Equals("Enumerable")
select symbol;
Assert.Equal(1, foundSymbol.Count());
solution = solution.RemoveMetadataReference(project1, mefReference);
assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference);
Assert.Null(assemblyReference);
await ValidateSolutionAndCompilationsAsync(solution);
}
private class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
public override void Initialize(AnalysisContext analysisContext)
{
}
}
[Fact]
public void TestProjectDiagnosticAnalyzers()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
Assert.Empty(solution.Projects.Single().AnalyzerReferences);
DiagnosticAnalyzer analyzer = new MockDiagnosticAnalyzer();
var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer));
// Test AddAnalyzer
var newSolution = solution.AddAnalyzerReference(project1, analyzerReference);
var actualAnalyzerReferences = newSolution.Projects.Single().AnalyzerReferences;
Assert.Equal(1, actualAnalyzerReferences.Count);
Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
var actualAnalyzers = actualAnalyzerReferences[0].GetAnalyzersForAllLanguages();
Assert.Equal(1, actualAnalyzers.Length);
Assert.Equal(analyzer, actualAnalyzers[0]);
// Test ProjectChanges
var changes = newSolution.GetChanges(solution).GetProjectChanges().Single();
var addedAnalyzerReference = changes.GetAddedAnalyzerReferences().Single();
Assert.Equal(analyzerReference, addedAnalyzerReference);
var removedAnalyzerReferences = changes.GetRemovedAnalyzerReferences();
Assert.Empty(removedAnalyzerReferences);
solution = newSolution;
// Test RemoveAnalyzer
solution = solution.RemoveAnalyzerReference(project1, analyzerReference);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Empty(actualAnalyzerReferences);
// Test AddAnalyzers
analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer));
DiagnosticAnalyzer secondAnalyzer = new MockDiagnosticAnalyzer();
var secondAnalyzerReference = new AnalyzerImageReference(ImmutableArray.Create(secondAnalyzer));
var analyzerReferences = new[] { analyzerReference, secondAnalyzerReference };
solution = solution.AddAnalyzerReferences(project1, analyzerReferences);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Equal(2, actualAnalyzerReferences.Count);
Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]);
solution = solution.RemoveAnalyzerReference(project1, analyzerReference);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Equal(1, actualAnalyzerReferences.Count);
Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[0]);
// Test WithAnalyzers
solution = solution.WithProjectAnalyzerReferences(project1, analyzerReferences);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Equal(2, actualAnalyzerReferences.Count);
Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]);
}
[Fact]
public void TestProjectParseOptions()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
solution = solution.AddMetadataReference(project1, s_mscorlib);
// Parse Options
var oldParseOptions = solution.GetProject(project1).ParseOptions;
var newParseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "AFTER" });
solution = solution.WithProjectParseOptions(project1, newParseOptions);
var newUpdatedParseOptions = solution.GetProject(project1).ParseOptions;
Assert.NotEqual(oldParseOptions, newUpdatedParseOptions);
Assert.Same(newParseOptions, newUpdatedParseOptions);
}
[Fact]
public async Task TestRemoveProjectAsync()
{
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp);
Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects");
Assert.NotNull(pid);
var project = sol.GetProject(pid);
Assert.False(project.HasDocuments);
var sol2 = sol.RemoveProject(pid);
Assert.False(sol2.ProjectIds.Any());
await ValidateSolutionAndCompilationsAsync(sol);
}
[Fact]
public async Task TestRemoveProjectWithReferencesAsync()
{
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
var pid2 = ProjectId.CreateNewId();
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp)
.AddProjectReference(pid2, new ProjectReference(pid));
Assert.Equal(2, sol.Projects.Count());
// remove the project that is being referenced
// this should leave a dangling reference
var sol2 = sol.RemoveProject(pid);
Assert.False(sol2.ContainsProject(pid));
Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2);
Assert.Equal(1, sol2.Projects.Count());
Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 project pid2 was expected to contain project reference " + pid);
await ValidateSolutionAndCompilationsAsync(sol2);
}
[Fact]
public async Task TestRemoveProjectWithReferencesAndAddItBackAsync()
{
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
var pid2 = ProjectId.CreateNewId();
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp)
.AddProjectReference(pid2, new ProjectReference(pid));
Assert.Equal(2, sol.Projects.Count());
// remove the project that is being referenced
var sol2 = sol.RemoveProject(pid);
Assert.False(sol2.ContainsProject(pid));
Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2);
Assert.Equal(1, sol2.Projects.Count());
Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 pid2 was expected to contain " + pid);
var sol3 = sol2.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp);
Assert.True(sol3.ContainsProject(pid), "sol3 was expected to contain " + pid);
Assert.True(sol3.ContainsProject(pid2), "sol3 was expected to contain " + pid2);
Assert.Equal(2, sol3.Projects.Count());
await ValidateSolutionAndCompilationsAsync(sol3);
}
[Fact]
public async Task TestGetSyntaxRootAsync()
{
var text = "public class Goo { }";
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var document = sol.GetDocument(did);
Assert.False(document.TryGetSyntaxRoot(out _));
var root = await document.GetSyntaxRootAsync();
Assert.NotNull(root);
Assert.Equal(text, root.ToString());
Assert.True(document.TryGetSyntaxRoot(out root));
Assert.NotNull(root);
}
[Fact]
public async Task TestUpdateDocumentAsync()
{
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
using var workspace = CreateWorkspace();
var solution1 = workspace.CurrentSolution
.AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp)
.AddDocument(documentId, "DocumentName", SourceText.From("class Class{}"));
var document = solution1.GetDocument(documentId);
var newRoot = await Formatter.FormatAsync(document).Result.GetSyntaxRootAsync();
var solution2 = solution1.WithDocumentSyntaxRoot(documentId, newRoot);
Assert.NotEqual(solution1, solution2);
var newText = solution2.GetDocument(documentId).GetTextAsync().Result.ToString();
Assert.Equal("class Class { }", newText);
}
[Fact]
public void TestUpdateSyntaxTreeWithAnnotations()
{
var text = "public class Goo { }";
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var document = sol.GetDocument(did);
var tree = document.GetSyntaxTreeAsync().Result;
var root = tree.GetRoot();
var annotation = new SyntaxAnnotation();
var annotatedRoot = root.WithAdditionalAnnotations(annotation);
var sol2 = sol.WithDocumentSyntaxRoot(did, annotatedRoot);
var doc2 = sol2.GetDocument(did);
var tree2 = doc2.GetSyntaxTreeAsync().Result;
var root2 = tree2.GetRoot();
// text should not be available yet (it should be defer created from the node)
// and getting the document or root should not cause it to be created.
Assert.False(tree2.TryGetText(out _));
var text2 = tree2.GetText();
Assert.NotNull(text2);
Assert.NotSame(tree, tree2);
Assert.NotSame(annotatedRoot, root2);
Assert.True(annotatedRoot.IsEquivalentTo(root2));
Assert.True(root2.HasAnnotation(annotation));
}
[Fact]
public void TestUpdatingFilePathUpdatesSyntaxTree()
{
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
const string OldFilePath = @"Z:\OldFilePath.cs";
const string NewFilePath = @"Z:\NewFilePath.cs";
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(documentId, "OldFilePath.cs", "public class Goo { }", filePath: OldFilePath);
// scope so later asserts don't accidentally use oldDocument
{
var oldDocument = solution.GetDocument(documentId);
Assert.Equal(OldFilePath, oldDocument.FilePath);
Assert.Equal(OldFilePath, oldDocument.GetSyntaxTreeAsync().Result.FilePath);
}
solution = solution.WithDocumentFilePath(documentId, NewFilePath);
{
var newDocument = solution.GetDocument(documentId);
Assert.Equal(NewFilePath, newDocument.FilePath);
Assert.Equal(NewFilePath, newDocument.GetSyntaxTreeAsync().Result.FilePath);
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestSyntaxRootNotKeptAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", "public class Goo { }");
var observedRoot = GetObservedSyntaxTreeRoot(sol, did);
observedRoot.AssertReleased();
// re-get the tree (should recover from storage, not reparse)
_ = sol.GetDocument(did).GetSyntaxRootAsync().Result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact]
[WorkItem(542736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542736")]
public void TestDocumentChangedOnDiskIsNotObserved()
{
var text1 = "public class A {}";
var text2 = "public class B {}";
var file = Temp.CreateFile().WriteAllText(text1, Encoding.UTF8);
// create a solution that evicts from the cache immediately.
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
var observedText = GetObservedText(sol, did, text1);
// change text on disk & verify it is changed
file.WriteAllText(text2);
var textOnDisk = file.ReadAllText();
Assert.Equal(text2, textOnDisk);
// stop observing it and let GC reclaim it
observedText.AssertReleased();
// if we ask for the same text again we should get the original content
var observedText2 = sol.GetDocument(did).GetTextAsync().Result;
Assert.Equal(text1, observedText2.ToString());
}
[Fact]
public void TestGetTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docText = doc.GetTextAsync().Result;
Assert.NotNull(docText);
Assert.Equal(text, docText.ToString());
}
[Fact]
public void TestGetLoadedTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
var doc = sol.GetDocument(did);
var docText = doc.GetTextAsync().Result;
Assert.NotNull(docText);
Assert.Equal(text, docText.ToString());
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/19427")]
public void TestGetRecoveredTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the text and then wait for the references to be GC'd
var observed = GetObservedText(sol, did, text);
observed.AssertReleased();
// get it async and force it to recover from temporary storage
var doc = sol.GetDocument(did);
var docText = doc.GetTextAsync().Result;
Assert.NotNull(docText);
Assert.Equal(text, docText.ToString());
}
[Fact]
public void TestGetSyntaxTreeAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docTree = doc.GetSyntaxTreeAsync().Result;
Assert.NotNull(docTree);
Assert.Equal(text, docTree.GetRoot().ToString());
}
[Fact]
public void TestGetSyntaxTreeFromLoadedTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
var doc = sol.GetDocument(did);
var docTree = doc.GetSyntaxTreeAsync().Result;
Assert.NotNull(docTree);
Assert.Equal(text, docTree.GetRoot().ToString());
}
[Fact]
public void TestGetSyntaxTreeFromAddedTree()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var tree = CSharp.SyntaxFactory.ParseSyntaxTree("public class C {}").GetRoot(CancellationToken.None);
tree = tree.WithAdditionalAnnotations(new SyntaxAnnotation("test"));
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", tree);
var doc = sol.GetDocument(did);
var docTree = doc.GetSyntaxRootAsync().Result;
Assert.NotNull(docTree);
Assert.True(tree.IsEquivalentTo(docTree));
Assert.NotNull(docTree.GetAnnotatedNodes("test").Single());
}
[Fact]
public async Task TestGetSyntaxRootAsync2Async()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docRoot = await doc.GetSyntaxRootAsync();
Assert.NotNull(docRoot);
Assert.Equal(text, docRoot.ToString());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/14954")]
public void TestGetRecoveredSyntaxRootAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the syntax tree root and wait for the references to be GC'd
var observed = GetObservedSyntaxTreeRoot(sol, did);
observed.AssertReleased();
// get it async and force it to be recovered from storage
var doc = sol.GetDocument(did);
var docRoot = doc.GetSyntaxRootAsync().Result;
Assert.NotNull(docRoot);
Assert.Equal(text, docRoot.ToString());
}
[Fact]
public void TestGetCompilationAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var proj = sol.GetProject(pid);
var compilation = proj.GetCompilationAsync().Result;
Assert.NotNull(compilation);
Assert.Equal(1, compilation.SyntaxTrees.Count());
}
[Fact]
public void TestGetSemanticModelAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docModel = doc.GetSemanticModelAsync().Result;
Assert.NotNull(docModel);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetTextDoesNotKeepTextAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the text and then wait for the references to be GC'd
var observed = GetObservedText(sol, did, text);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SourceText> GetObservedText(Solution solution, DocumentId documentId, string expectedText = null)
{
var observedText = solution.GetDocument(documentId).GetTextAsync().Result;
if (expectedText != null)
{
Assert.Equal(expectedText, observedText.ToString());
}
return new ObjectReference<SourceText>(observedText);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetTextAsyncDoesNotKeepTextAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the text and then wait for the references to be GC'd
var observed = GetObservedTextAsync(sol, did, text);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SourceText> GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null)
{
var observedText = solution.GetDocument(documentId).GetTextAsync().Result;
if (expectedText != null)
{
Assert.Equal(expectedText, observedText.ToString());
}
return new ObjectReference<SourceText>(observedText);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetSyntaxRootDoesNotKeepRootAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedSyntaxTreeRoot(sol, did);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRoot(Solution solution, DocumentId documentId)
{
var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result;
return new ObjectReference<SyntaxNode>(observedTree);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetSyntaxRootAsyncDoesNotKeepRootAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedSyntaxTreeRootAsync(sol, did);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRootAsync(Solution solution, DocumentId documentId)
{
var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result;
return new ObjectReference<SyntaxNode>(observedTree);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13506")]
[WorkItem(13506, "https://github.com/dotnet/roslyn/issues/13506")]
public void TestRecoverableSyntaxTreeCSharp()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = @"public class C {
public void Method1() {}
public void Method2() {}
public void Method3() {}
public void Method4() {}
public void Method5() {}
public void Method6() {}
}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
TestRecoverableSyntaxTree(sol, did);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestRecoverableSyntaxTreeVisualBasic()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = @"Public Class C
Sub Method1()
End Sub
Sub Method2()
End Sub
Sub Method3()
End Sub
Sub Method4()
End Sub
Sub Method5()
End Sub
Sub Method6()
End Sub
End Class";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.VisualBasic)
.AddDocument(did, "goo.vb", text);
TestRecoverableSyntaxTree(sol, did);
}
private static void TestRecoverableSyntaxTree(Solution sol, DocumentId did)
{
// get it async and wait for it to get GC'd
var observed = GetObservedSyntaxTreeRootAsync(sol, did);
observed.AssertReleased();
var doc = sol.GetDocument(did);
// access the tree & root again (recover it)
var tree = doc.GetSyntaxTreeAsync().Result;
// this should cause reparsing
var root = tree.GetRoot();
// prove that the new root is correctly associated with the tree
Assert.Equal(tree, root.SyntaxTree);
// reset the syntax root, to make it 'refactored' by adding an attribute
var newRoot = doc.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation);
var doc2 = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot, PreservationMode.PreserveValue).GetDocument(doc.Id);
// get it async and wait for it to get GC'd
var observed2 = GetObservedSyntaxTreeRootAsync(doc2.Project.Solution, did);
observed2.AssertReleased();
// access the tree & root again (recover it)
var tree2 = doc2.GetSyntaxTreeAsync().Result;
// this should cause deserialization
var root2 = tree2.GetRoot();
// prove that the new root is correctly associated with the tree
Assert.Equal(tree2, root2.SyntaxTree);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetCompilationAsyncDoesNotKeepCompilationAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedCompilationAsync(sol, pid);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<Compilation> GetObservedCompilationAsync(Solution solution, ProjectId projectId)
{
var observed = solution.GetProject(projectId).GetCompilationAsync().Result;
return new ObjectReference<Compilation>(observed);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetCompilationDoesNotKeepCompilationAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedCompilation(sol, pid);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<Compilation> GetObservedCompilation(Solution solution, ProjectId projectId)
{
var observed = solution.GetProject(projectId).GetCompilationAsync().Result;
return new ObjectReference<Compilation>(observed);
}
[Fact]
public void TestWorkspaceLanguageServiceOverride()
{
var hostServices = FeaturesTestCompositions.Features.AddParts(new[]
{
typeof(TestLanguageServiceA),
typeof(TestLanguageServiceB),
}).GetHostServices();
var ws = new AdhocWorkspace(hostServices, ServiceLayer.Host);
var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
Assert.NotNull(service as TestLanguageServiceA);
var ws2 = new AdhocWorkspace(hostServices, "Quasimodo");
var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
Assert.NotNull(service2 as TestLanguageServiceB);
}
#if false
[Fact]
public void TestSolutionInfo()
{
var oldSolutionId = SolutionId.CreateNewId("oldId");
var oldVersion = VersionStamp.Create();
var solutionInfo = SolutionInfo.Create(oldSolutionId, oldVersion, null, null);
var newSolutionId = SolutionId.CreateNewId("newId");
solutionInfo = solutionInfo.WithId(newSolutionId);
Assert.NotEqual(oldSolutionId, solutionInfo.Id);
Assert.Equal(newSolutionId, solutionInfo.Id);
var newVersion = oldVersion.GetNewerVersion();
solutionInfo = solutionInfo.WithVersion(newVersion);
Assert.NotEqual(oldVersion, solutionInfo.Version);
Assert.Equal(newVersion, solutionInfo.Version);
Assert.Null(solutionInfo.FilePath);
var newFilePath = @"C:\test\fake.sln";
solutionInfo = solutionInfo.WithFilePath(newFilePath);
Assert.Equal(newFilePath, solutionInfo.FilePath);
Assert.Equal(0, solutionInfo.Projects.Count());
}
#endif
private interface ITestLanguageService : ILanguageService
{
}
[ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, ServiceLayer.Default), Shared, PartNotDiscoverable]
private class TestLanguageServiceA : ITestLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLanguageServiceA()
{
}
}
[ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, "Quasimodo"), Shared, PartNotDiscoverable]
private class TestLanguageServiceB : ITestLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLanguageServiceB()
{
}
}
[Fact]
[WorkItem(666263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666263")]
public async Task TestDocumentFileAccessFailureMissingFile()
{
var workspace = new AdhocWorkspace();
var solution = workspace.CurrentSolution;
WorkspaceDiagnostic diagnosticFromEvent = null;
solution.Workspace.WorkspaceFailed += (sender, args) =>
{
diagnosticFromEvent = args.Diagnostic;
};
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
solution = solution.AddProject(pid, "goo", "goo", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8))
.WithDocumentFilePath(did, "document path");
var doc = solution.GetDocument(did);
var text = await doc.GetTextAsync().ConfigureAwait(false);
var diagnostic = await doc.State.GetLoadDiagnosticAsync(CancellationToken.None).ConfigureAwait(false);
Assert.Equal(@"C:\doesnotexist.cs: (0,0)-(0,0)", diagnostic.Location.GetLineSpan().ToString());
Assert.Equal(WorkspaceDiagnosticKind.Failure, diagnosticFromEvent.Kind);
Assert.Equal("", text.ToString());
// Verify invariant: The compilation is guaranteed to have a syntax tree for each document of the project (even if the contnet fails to load).
var compilation = await solution.State.GetCompilationAsync(doc.Project.State, CancellationToken.None).ConfigureAwait(false);
var syntaxTree = compilation.SyntaxTrees.Single();
Assert.Equal("", syntaxTree.ToString());
}
[Fact]
public void TestGetProjectForAssemblySymbol()
{
var pid1 = ProjectId.CreateNewId("p1");
var pid2 = ProjectId.CreateNewId("p2");
var pid3 = ProjectId.CreateNewId("p3");
var did1 = DocumentId.CreateNewId(pid1);
var did2 = DocumentId.CreateNewId(pid2);
var did3 = DocumentId.CreateNewId(pid3);
var text1 = @"
Public Class A
End Class";
var text2 = @"
Public Class B
End Class
";
var text3 = @"
public class C : B {
}
";
var text4 = @"
public class C : A {
}
";
var solution = new AdhocWorkspace().CurrentSolution
.AddProject(pid1, "GooA", "Goo.dll", LanguageNames.VisualBasic)
.AddDocument(did1, "A.vb", text1)
.AddMetadataReference(pid1, s_mscorlib)
.AddProject(pid2, "GooB", "Goo2.dll", LanguageNames.VisualBasic)
.AddDocument(did2, "B.vb", text2)
.AddMetadataReference(pid2, s_mscorlib)
.AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp)
.AddDocument(did3, "C.cs", text3)
.AddMetadataReference(pid3, s_mscorlib)
.AddProjectReference(pid3, new ProjectReference(pid1))
.AddProjectReference(pid3, new ProjectReference(pid2));
var project3 = solution.GetProject(pid3);
var comp3 = project3.GetCompilationAsync().Result;
var classC = comp3.GetTypeByMetadataName("C");
var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly);
Assert.Equal(pid2, projectForBaseType.Id);
// switch base type to A then try again
var solution2 = solution.WithDocumentText(did3, SourceText.From(text4));
project3 = solution2.GetProject(pid3);
comp3 = project3.GetCompilationAsync().Result;
classC = comp3.GetTypeByMetadataName("C");
projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly);
Assert.Equal(pid1, projectForBaseType.Id);
}
[WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")]
[Fact]
public void TestEncodingRetainedAfterTreeChanged()
{
var ws = new AdhocWorkspace();
var proj = ws.AddProject("proj", LanguageNames.CSharp);
var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32));
Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding);
// updating root doesn't change original encoding
var root = doc.GetSyntaxRootAsync().Result;
var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace(" ")));
var newDoc = doc.WithSyntaxRoot(newRoot);
Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding);
}
[Fact]
public void TestProjectWithNoBrokenReferencesHasNoIncompleteReferences()
{
var workspace = new AdhocWorkspace();
var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
var project2 = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(project1.Id) }));
// Nothing should have incomplete references, and everything should build
Assert.True(project1.HasSuccessfullyLoadedAsync().Result);
Assert.True(project2.HasSuccessfullyLoadedAsync().Result);
Assert.Single(project2.GetCompilationAsync().Result.ExternalReferences);
}
[Fact]
public void TestProjectWithBrokenCrossLanguageReferenceHasIncompleteReferences()
{
var workspace = new AdhocWorkspace();
var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class "));
var project2 = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(project1.Id) }));
Assert.True(project1.HasSuccessfullyLoadedAsync().Result);
Assert.False(project2.HasSuccessfullyLoadedAsync().Result);
Assert.Empty(project2.GetCompilationAsync().Result.ExternalReferences);
}
[Fact]
public async Task TestFrozenPartialProjectHasDifferentSemanticVersions()
{
using var workspace = CreateWorkspaceWithPartalSemantics();
var project = workspace.CurrentSolution.AddProject("CSharpProject", "CSharpProject", LanguageNames.CSharp);
project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
var documentToFreeze = project.AddDocument("DocumentToFreeze.cs", SourceText.From(""));
var frozenDocument = documentToFreeze.WithFrozenPartialSemantics(CancellationToken.None);
// Because we had no compilation produced yet, we expect that only the DocumentToFreeze is in the compilation
Assert.NotSame(frozenDocument, documentToFreeze);
var tree = Assert.Single((await frozenDocument.Project.GetCompilationAsync()).SyntaxTrees);
Assert.Equal("DocumentToFreeze.cs", tree.FilePath);
// Versions should be different
Assert.NotEqual(
await documentToFreeze.Project.GetDependentSemanticVersionAsync(),
await frozenDocument.Project.GetDependentSemanticVersionAsync());
Assert.NotEqual(
await documentToFreeze.Project.GetSemanticVersionAsync(),
await frozenDocument.Project.GetSemanticVersionAsync());
}
[Fact]
public void TestFrozenPartialProjectAlwaysIsIncomplete()
{
var workspace = new AdhocWorkspace();
var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
var project2 = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(project1.Id) }));
var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From(""));
// Nothing should have incomplete references, and everything should build
var frozenSolution = document.WithFrozenPartialSemantics(CancellationToken.None).Project.Solution;
Assert.True(frozenSolution.GetProject(project1.Id).HasSuccessfullyLoadedAsync().Result);
Assert.True(frozenSolution.GetProject(project2.Id).HasSuccessfullyLoadedAsync().Result);
}
[Fact]
public void TestProjectCompletenessWithMultipleProjects()
{
GetMultipleProjects(out var csBrokenProject, out var vbNormalProject, out var dependsOnBrokenProject, out var dependsOnVbNormalProject, out var transitivelyDependsOnBrokenProjects, out var transitivelyDependsOnNormalProjects);
// check flag for a broken project itself
Assert.False(csBrokenProject.HasSuccessfullyLoadedAsync().Result);
// check flag for a normal project itself
Assert.True(vbNormalProject.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that directly reference a broken project
Assert.True(dependsOnBrokenProject.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that directly reference only normal project
Assert.True(dependsOnVbNormalProject.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that indirectly reference a borken project
// normal project -> normal project -> broken project
Assert.True(transitivelyDependsOnBrokenProjects.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that indirectly reference only normal project
// normal project -> normal project -> normal project
Assert.True(transitivelyDependsOnNormalProjects.HasSuccessfullyLoadedAsync().Result);
}
[Fact]
public async Task TestMassiveFileSize()
{
// set max file length to 1 bytes
var maxLength = 1;
var workspace = new AdhocWorkspace();
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FileTextLoaderOptions.FileLengthThreshold, maxLength)));
using var root = new TempRoot();
var file = root.CreateFile(prefix: "massiveFile", extension: ".cs").WriteAllText("hello");
var loader = new FileTextLoader(file.Path, Encoding.UTF8);
var textLength = FileUtilities.GetFileLength(file.Path);
var expected = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, file.Path, textLength, maxLength);
var exceptionThrown = false;
try
{
// test async one
var unused = await loader.LoadTextAndVersionAsync(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None);
}
catch (InvalidDataException ex)
{
exceptionThrown = true;
Assert.Equal(expected, ex.Message);
}
Assert.True(exceptionThrown);
exceptionThrown = false;
try
{
// test sync one
var unused = loader.LoadTextAndVersionSynchronously(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None);
}
catch (InvalidDataException ex)
{
exceptionThrown = true;
Assert.Equal(expected, ex.Message);
}
Assert.True(exceptionThrown);
}
[Fact]
[WorkItem(18697, "https://github.com/dotnet/roslyn/issues/18697")]
public void TestWithSyntaxTree()
{
// get one to get to syntax tree factory
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var solution = workspace.CurrentSolution;
var dummyProject = solution.AddProject("dummy", "dummy", LanguageNames.CSharp);
var factory = dummyProject.LanguageServices.SyntaxTreeFactory;
// create the origin tree
var strongTree = factory.ParseSyntaxTree("dummy", dummyProject.ParseOptions, SourceText.From("// emtpy"), CancellationToken.None);
// create recoverable tree off the original tree
var recoverableTree = factory.CreateRecoverableTree(
dummyProject.Id,
strongTree.FilePath,
strongTree.Options,
new ConstantValueSource<TextAndVersion>(TextAndVersion.Create(strongTree.GetText(), VersionStamp.Create(), strongTree.FilePath)),
strongTree.GetText().Encoding,
strongTree.GetRoot());
// create new tree before it ever getting root node
var newTree = recoverableTree.WithFilePath("different/dummy");
// this shouldn't throw
_ = newTree.GetRoot();
}
[Fact]
public void TestUpdateDocumentsOrder()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
VersionStamp GetVersion() => solution.GetProject(pid).Version;
ImmutableArray<DocumentId> GetDocumentIds() => solution.GetProject(pid).DocumentIds.ToImmutableArray();
ImmutableArray<SyntaxTree> GetSyntaxTrees()
{
return solution.GetProject(pid).GetCompilationAsync().Result.SyntaxTrees.ToImmutableArray();
}
solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp);
var text1 = "public class Test1 {}";
var did1 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did1, "test1.cs", text1);
var text2 = "public class Test2 {}";
var did2 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did2, "test2.cs", text2);
var text3 = "public class Test3 {}";
var did3 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did3, "test3.cs", text3);
var text4 = "public class Test4 {}";
var did4 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did4, "test4.cs", text4);
var text5 = "public class Test5 {}";
var did5 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did5, "test5.cs", text5);
var oldVersion = GetVersion();
solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 }));
var newVersion = GetVersion();
// Make sure we have a new version because the order changed.
Assert.NotEqual(oldVersion, newVersion);
var documentIds = GetDocumentIds();
Assert.Equal(did5, documentIds[0]);
Assert.Equal(did4, documentIds[1]);
Assert.Equal(did3, documentIds[2]);
Assert.Equal(did2, documentIds[3]);
Assert.Equal(did1, documentIds[4]);
var syntaxTrees = GetSyntaxTrees();
Assert.Equal(documentIds.Count(), syntaxTrees.Count());
Assert.Equal("test5.cs", syntaxTrees[0].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test4.cs", syntaxTrees[1].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test3.cs", syntaxTrees[2].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test2.cs", syntaxTrees[3].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test1.cs", syntaxTrees[4].FilePath, StringComparer.OrdinalIgnoreCase);
solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 }));
var newSameVersion = GetVersion();
// Make sure we have the same new version because the order hasn't changed.
Assert.Equal(newVersion, newSameVersion);
}
[Fact]
public void TestUpdateDocumentsOrderExceptions()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp);
var text1 = "public class Test1 {}";
var did1 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did1, "test1.cs", text1);
var text2 = "public class Test2 {}";
var did2 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did2, "test2.cs", text2);
var text3 = "public class Test3 {}";
var did3 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did3, "test3.cs", text3);
var text4 = "public class Test4 {}";
var did4 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did4, "test4.cs", text4);
var text5 = "public class Test5 {}";
var did5 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did5, "test5.cs", text5);
solution = solution.RemoveDocument(did5);
Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.Create<DocumentId>()));
Assert.Throws<ArgumentNullException>(() => solution = solution.WithProjectDocumentsOrder(pid, null));
Assert.Throws<InvalidOperationException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did3, did2, did1 })));
Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did3, did2, did1 })));
}
[Theory]
[CombinatorialData]
public async Task TestAddingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName)
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb";
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", languageName);
solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension);
var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync();
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var project = solution.GetProject(projectId);
var newCompilation = await project.GetCompilationAsync();
Assert.Same(originalSyntaxTree, newSyntaxTree);
Assert.NotSame(originalCompilation, newCompilation);
Assert.NotEqual(originalCompilation.Options, newCompilation.Options);
var provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.True(provider.TryGetDiagnosticValue(newSyntaxTree, "CA1234", CancellationToken.None, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
}
[Theory]
[CombinatorialData]
public async Task TestAddingAndRemovingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName)
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb";
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", languageName);
solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension);
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var syntaxTreeAfterAddingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var project = solution.GetProject(projectId);
var provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.True(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId);
project = solution.GetProject(projectId);
var syntaxTreeAfterRemovingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.False(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out _));
var finalCompilation = await project.GetCompilationAsync();
Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterRemovingEditorConfig));
}
[Theory]
[CombinatorialData]
public async Task TestChangingAnEditorConfigFile([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName, bool useRecoverableTrees)
{
using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace();
var solution = workspace.CurrentSolution;
var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb";
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", languageName);
solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension);
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var syntaxTreeBeforeEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var project = solution.GetProject(projectId);
var provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider);
Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA1234", CancellationToken.None, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
solution = solution.WithAnalyzerConfigDocumentTextLoader(
editorConfigDocumentId,
TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA6789.severity = error"), VersionStamp.Default)),
PreservationMode.PreserveValue);
var syntaxTreeAfterEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
project = solution.GetProject(projectId);
provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider);
Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA6789", CancellationToken.None, out severity));
Assert.Equal(ReportDiagnostic.Error, severity);
var finalCompilation = await project.GetCompilationAsync();
Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterEditorConfigChange));
}
[Fact]
public void TestAddingAndRemovingGlobalEditorConfigFileWithDiagnosticSeverity()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp);
solution = solution.AddDocument(sourceDocumentId, "Test.cs", "", filePath: @"Z:\Test.cs");
var originalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider;
Assert.False(originalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _));
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".globalconfig",
filePath: @"Z:\.globalconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("is_global = true\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var newProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider;
Assert.True(newProvider.TryGetGlobalDiagnosticValue("CA1234", default, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId);
var finalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider;
Assert.False(finalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _));
}
[Fact]
[WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")]
public async Task TestAddingEditorConfigFileWithIsGeneratedCodeOption()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp)
.WithProjectMetadataReferences(projectId, new[] { TestMetadata.Net451.mscorlib })
.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable));
var src = @"
class C
{
void M(C? c)
{
_ = c.ToString(); // warning CS8602: Dereference of a possibly null reference.
}
}";
solution = solution.AddDocument(sourceDocumentId, "Test.cs", src, filePath: @"Z:\Test.cs");
var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync();
// warning CS8602: Dereference of a possibly null reference.
var diagnostics = originalCompilation.GetDiagnostics();
var diagnostic = Assert.Single(diagnostics);
Assert.Equal("CS8602", diagnostic.Id);
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ngenerated_code = true"), VersionStamp.Default)))));
var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var newCompilation = await solution.GetProject(projectId).GetCompilationAsync();
Assert.Same(originalSyntaxTree, newSyntaxTree);
Assert.NotSame(originalCompilation, newCompilation);
Assert.NotEqual(originalCompilation.Options, newCompilation.Options);
// warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// Auto-generated code requires an explicit '#nullable' directive in source.
diagnostics = newCompilation.GetDiagnostics();
diagnostic = Assert.Single(diagnostics);
Assert.Contains("CS8669", diagnostic.Id);
}
[Fact]
public void NoCompilationProjectsHaveNullSyntaxTreesAndSemanticModels()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName);
solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt");
var document = solution.GetDocument(documentId)!;
Assert.False(document.TryGetSyntaxTree(out _));
Assert.Null(document.GetSyntaxTreeAsync().Result);
Assert.Null(document.GetSyntaxTreeSynchronously(CancellationToken.None));
Assert.False(document.TryGetSemanticModel(out _));
Assert.Null(document.GetSemanticModelAsync().Result);
}
[Fact]
public void ChangingFilePathOfFileInNoCompilationProjectWorks()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName);
solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt");
Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result);
solution = solution.WithDocumentFilePath(documentId, @"Z:\NewPath.txt");
Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result);
}
[Fact]
public void AddingAndRemovingProjectsUpdatesFilePathMap()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
const string editorConfigFilePath = @"Z:\.editorconfig";
var projectInfo =
ProjectInfo.Create(projectId, VersionStamp.Default, "Test", "Test", LanguageNames.CSharp)
.WithAnalyzerConfigDocuments(new[] { DocumentInfo.Create(editorConfigDocumentId, ".editorconfig", filePath: editorConfigFilePath) });
solution = solution.AddProject(projectInfo);
Assert.Equal(editorConfigDocumentId, Assert.Single(solution.GetDocumentIdsWithFilePath(editorConfigFilePath)));
solution = solution.RemoveProject(projectId);
Assert.Empty(solution.GetDocumentIdsWithFilePath(editorConfigFilePath));
}
private static void GetMultipleProjects(
out Project csBrokenProject,
out Project vbNormalProject,
out Project dependsOnBrokenProject,
out Project dependsOnVbNormalProject,
out Project transitivelyDependsOnBrokenProjects,
out Project transitivelyDependsOnNormalProjects)
{
var workspace = new AdhocWorkspace();
csBrokenProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"CSharpProject",
"CSharpProject",
LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false));
vbNormalProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic));
dependsOnBrokenProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(csBrokenProject.Id), new ProjectReference(vbNormalProject.Id) }));
dependsOnVbNormalProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"CSharpProject",
"CSharpProject",
LanguageNames.CSharp,
projectReferences: new[] { new ProjectReference(vbNormalProject.Id) }));
transitivelyDependsOnBrokenProjects = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"CSharpProject",
"CSharpProject",
LanguageNames.CSharp,
projectReferences: new[] { new ProjectReference(dependsOnBrokenProject.Id) }));
transitivelyDependsOnNormalProjects = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(dependsOnVbNormalProject.Id) }));
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestOptionChangesForLanguagesNotInSolution()
{
// Create an empty solution with no projects.
using var workspace = CreateWorkspace();
var s0 = workspace.CurrentSolution;
var optionService = workspace.Services.GetRequiredService<IOptionService>();
// Apply an option change to a C# option.
var option = GenerationOptions.PlaceSystemNamespaceFirst;
var defaultValue = option.DefaultValue;
var changedValue = !defaultValue;
var options = s0.Options.WithChangedOption(option, LanguageNames.CSharp, changedValue);
// Verify option change is preserved even if the solution has no project with that language.
var s1 = s0.WithOptions(options);
VerifyOptionSet(s1.Options);
// Verify option value is preserved on adding a project for a different language.
var s2 = s1.AddProject("P1", "A1", LanguageNames.VisualBasic).Solution;
VerifyOptionSet(s2.Options);
// Verify option value is preserved on roundtriping the option set (serialize and deserialize).
var s3 = s2.AddProject("P2", "A2", LanguageNames.CSharp).Solution;
var roundTripOptionSet = SerializeAndDeserialize((SerializableOptionSet)s3.Options, optionService);
VerifyOptionSet(roundTripOptionSet);
// Verify option value is preserved on removing a project.
var s4 = s3.RemoveProject(s3.Projects.Single(p => p.Name == "P2").Id);
VerifyOptionSet(s4.Options);
return;
void VerifyOptionSet(OptionSet optionSet)
{
Assert.Equal(changedValue, optionSet.GetOption(option, LanguageNames.CSharp));
Assert.Equal(defaultValue, optionSet.GetOption(option, LanguageNames.VisualBasic));
}
static SerializableOptionSet SerializeAndDeserialize(SerializableOptionSet optionSet, IOptionService optionService)
{
using var stream = new MemoryStream();
using var writer = new ObjectWriter(stream);
optionSet.Serialize(writer, CancellationToken.None);
stream.Position = 0;
using var reader = ObjectReader.TryGetReader(stream);
return SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None);
}
}
[Theory]
[CombinatorialData]
public async Task TestUpdatedDocumentTextIsObservablyConstantAsync(bool recoverable)
{
using var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace();
var pid = ProjectId.CreateNewId();
var text = SourceText.From("public class C { }");
var version = VersionStamp.Create();
var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
var projInfo = ProjectInfo.Create(
pid,
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp,
documents: new[] { docInfo });
var solution = workspace.CurrentSolution.AddProject(projInfo);
var doc = solution.GetDocument(docInfo.Id);
// change document
var root = await doc.GetSyntaxRootAsync();
var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());
Assert.NotSame(root, newRoot);
var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id);
Assert.NotSame(doc, newDoc);
var newDocText = await newDoc.GetTextAsync();
var sameText = await newDoc.GetTextAsync();
Assert.Same(newDocText, sameText);
var newDocTree = await newDoc.GetSyntaxTreeAsync();
var treeText = newDocTree.GetText();
Assert.Same(newDocText, treeText);
}
[Fact]
public async Task ReplacingTextMultipleTimesDoesNotRootIntermediateCopiesIfCompilationNotAskedFor()
{
// This test replicates the pattern of some operation changing a bunch of files, but the files aren't kept open.
// In Visual Studio we do large refactorings by opening files with an invisible editor, making changes, and closing
// again. This process means we'll queue up intermediate changes to those files, but we don't want to hold onto
// the intermediate edits when we don't really need to since the final version will be all that matters.
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
// Fetch the compilation, so further edits are going to be incremental updates of this one
var originalCompilation = await solution.Projects.Single().GetCompilationAsync();
// Create a source text we'll release and ensure it disappears. We'll also make sure we don't accidentally root
// that solution in the middle.
var sourceTextToRelease = ObjectReference.CreateFromFactory(static () => SourceText.From(Guid.NewGuid().ToString()));
var solutionWithSourceTextToRelease = sourceTextToRelease.GetObjectReference(
static (sourceText, document) => document.Project.Solution.WithDocumentText(document.Id, sourceText, PreservationMode.PreserveIdentity),
solution.GetDocument(documentId));
// Change it again, this time by editing the text loader; this replicates us closing a file, and we don't want to pin the changes from the
// prior change.
var finalSolution = solutionWithSourceTextToRelease.GetObjectReference(
static (s, documentId) => s.WithDocumentTextLoader(documentId, new TestTextLoader(Guid.NewGuid().ToString()), PreservationMode.PreserveValue), documentId).GetReference();
// The text in the middle shouldn't be held at all, since we replaced it.
solutionWithSourceTextToRelease.ReleaseStrongReference();
sourceTextToRelease.AssertReleased();
GC.KeepAlive(finalSolution);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Persistence;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.VisualStudio.Threading;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.Workspace)]
public class SolutionTests : TestBase
{
#nullable enable
private static readonly MetadataReference s_mscorlib = TestMetadata.Net451.mscorlib;
private static readonly DocumentId s_unrelatedDocumentId = DocumentId.CreateNewId(ProjectId.CreateNewId());
private static Workspace CreateWorkspaceWithProjectAndDocuments()
{
var projectId = ProjectId.CreateNewId();
var workspace = CreateWorkspace();
Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp)
.AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }")
.AddAdditionalDocument(DocumentId.CreateNewId(projectId), "add.txt", "text")
.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"), filePath: "/a/b")));
return workspace;
}
private static IEnumerable<T> EmptyEnumerable<T>()
{
yield break;
}
// Returns an enumerable that can only be enumerated once.
private static IEnumerable<T> OnceEnumerable<T>(params T[] items)
=> OnceEnumerableImpl(new StrongBox<int>(), items);
private static IEnumerable<T> OnceEnumerableImpl<T>(StrongBox<int> counter, T[] items)
{
Assert.Equal(0, counter.Value);
counter.Value++;
foreach (var item in items)
{
yield return item;
}
}
[Fact]
public void RemoveDocument_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveDocument(null!));
Assert.Throws<InvalidOperationException>(() => solution.RemoveDocument(s_unrelatedDocumentId));
}
[Fact]
public void RemoveDocuments_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(default));
Assert.Throws<InvalidOperationException>(() => solution.RemoveDocuments(ImmutableArray.Create(s_unrelatedDocumentId)));
Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(ImmutableArray.Create((DocumentId)null!)));
}
[Fact]
public void RemoveAdditionalDocument_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocument(null!));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocument(s_unrelatedDocumentId));
}
[Fact]
public void RemoveAdditionalDocuments_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(default));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create(s_unrelatedDocumentId)));
Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create((DocumentId)null!)));
}
[Fact]
public void RemoveAnalyzerConfigDocument_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocument(null!));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocument(s_unrelatedDocumentId));
}
[Fact]
public void RemoveAnalyzerConfigDocuments_Errors()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(default));
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create(s_unrelatedDocumentId)));
Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create((DocumentId)null!)));
}
[Fact]
public void WithDocumentName()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var name = "new name";
var newSolution1 = solution.WithDocumentName(documentId, name);
Assert.Equal(name, newSolution1.GetDocument(documentId)!.Name);
var newSolution2 = newSolution1.WithDocumentName(documentId, name);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(documentId, name: null!));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(null!, name));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentName(s_unrelatedDocumentId, name));
}
[Fact]
public void WithDocumentFolders()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var folders = new[] { "folder1", "folder2" };
var newSolution1 = solution.WithDocumentFolders(documentId, folders);
Assert.Equal(folders, newSolution1.GetDocument(documentId)!.Folders);
var newSolution2 = newSolution1.WithDocumentFolders(documentId, folders);
Assert.Same(newSolution2, newSolution1);
// empty:
var newSolution3 = solution.WithDocumentFolders(documentId, new string[0]);
Assert.Equal(new string[0], newSolution3.GetDocument(documentId)!.Folders);
var newSolution4 = solution.WithDocumentFolders(documentId, ImmutableArray<string>.Empty);
Assert.Same(newSolution3, newSolution4);
var newSolution5 = solution.WithDocumentFolders(documentId, null);
Assert.Same(newSolution3, newSolution5);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(documentId, folders: new string[] { null! }));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(null!, folders));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFolders(s_unrelatedDocumentId, folders));
}
[Fact]
[WorkItem(34837, "https://github.com/dotnet/roslyn/issues/34837")]
[WorkItem(37125, "https://github.com/dotnet/roslyn/issues/37125")]
public void WithDocumentFilePath()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var path = "new path";
var newSolution1 = solution.WithDocumentFilePath(documentId, path);
Assert.Equal(path, newSolution1.GetDocument(documentId)!.FilePath);
AssertEx.Equal(new[] { documentId }, newSolution1.GetDocumentIdsWithFilePath(path));
var newSolution2 = newSolution1.WithDocumentFilePath(documentId, path);
Assert.Same(newSolution1, newSolution2);
// empty path (TODO https://github.com/dotnet/roslyn/issues/37125):
var newSolution3 = solution.WithDocumentFilePath(documentId, "");
Assert.Equal("", newSolution3.GetDocument(documentId)!.FilePath);
Assert.Empty(newSolution3.GetDocumentIdsWithFilePath(""));
// TODO: https://github.com/dotnet/roslyn/issues/37125
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(documentId, filePath: null!));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(null!, path));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFilePath(s_unrelatedDocumentId, path));
}
[Fact]
public void WithSourceCodeKind()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
Assert.Same(solution, solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Regular));
var newSolution1 = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Script);
Assert.Equal(SourceCodeKind.Script, newSolution1.GetDocument(documentId)!.SourceCodeKind);
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSourceCodeKind(documentId, (SourceCodeKind)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSourceCodeKind(null!, SourceCodeKind.Script));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSourceCodeKind(s_unrelatedDocumentId, SourceCodeKind.Script));
}
[Fact, Obsolete]
public void WithSourceCodeKind_Obsolete()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var newSolution = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Interactive);
Assert.Equal(SourceCodeKind.Script, newSolution.GetDocument(documentId)!.SourceCodeKind);
}
[Fact]
public void WithDocumentSyntaxRoot()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var root = CS.SyntaxFactory.ParseSyntaxTree("class NewClass {}").GetRoot();
var newSolution1 = solution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetSyntaxRoot(out var actualRoot));
Assert.Equal(root.ToString(), actualRoot!.ToString());
// the actual root has a new parent SyntaxTree:
Assert.NotSame(root, actualRoot);
var newSolution2 = newSolution1.WithDocumentSyntaxRoot(documentId, actualRoot);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSyntaxRoot(documentId, root, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSyntaxRoot(null!, root));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSyntaxRoot(s_unrelatedDocumentId, root));
}
[Fact]
[WorkItem(37125, "https://github.com/dotnet/roslyn/issues/41940")]
public async Task WithDocumentSyntaxRoot_AnalyzerConfigWithoutFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }")
.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"));
var project = solution.GetProject(projectId)!;
var compilation = (await project.GetCompilationAsync())!;
var tree = compilation.SyntaxTrees.Single();
var provider = compilation.Options.SyntaxTreeOptionsProvider!;
Assert.Throws<ArgumentException>(() => provider.TryGetDiagnosticValue(tree, "CA1234", CancellationToken.None, out _));
}
[Fact]
public void WithDocumentText_SourceText()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, text, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithDocumentText_TextAndVersion()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
var newSolution1 = solution.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
Assert.True(newSolution1.GetDocument(documentId)!.TryGetTextVersion(out var actualVersion));
Assert.Same(textAndVersion.Text, actualText);
Assert.Equal(textAndVersion.Version, actualVersion);
var newSolution2 = newSolution1.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, textAndVersion, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithDocumentText_MultipleDocuments()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
// documents not in solution are skipped: https://github.com/dotnet/roslyn/issues/42029
Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { null! }, text));
Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { s_unrelatedDocumentId }, text));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId[])null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(new[] { documentId }, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(new[] { documentId }, text, (PreservationMode)(-1)));
}
[Fact]
public void WithAdditionalDocumentText_SourceText()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AdditionalDocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, text, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAdditionalDocumentText_TextAndVersion()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AdditionalDocumentIds.Single();
var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
var newSolution1 = solution.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText));
Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetTextVersion(out var actualVersion));
Assert.Same(textAndVersion.Text, actualText);
Assert.Equal(textAndVersion.Version, actualVersion);
var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, textAndVersion, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAnalyzerConfigDocumentText_SourceText()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single();
var text = SourceText.From("new text");
var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText));
Assert.Same(text, actualText);
var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, text, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAnalyzerConfigDocumentText_TextAndVersion()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single();
var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText));
Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetTextVersion(out var actualVersion));
Assert.Same(textAndVersion.Text, actualText);
Assert.Equal(textAndVersion.Version, actualVersion);
var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity);
Assert.Same(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithDocumentTextLoader()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
var loader = new TestTextLoader("new text");
var newSolution1 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.Equal("new text", newSolution1.GetDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString());
// Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028
var newSolution2 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.NotSame(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentTextLoader(documentId, loader, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAdditionalDocumentTextLoader()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AdditionalDocumentIds.Single();
var loader = new TestTextLoader("new text");
var newSolution1 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.Equal("new text", newSolution1.GetAdditionalDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString());
// Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028
var newSolution2 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.NotSame(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentTextLoader(documentId, loader, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithAnalyzerConfigDocumentTextLoader()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single();
var loader = new TestTextLoader("new text");
var newSolution1 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.Equal("new text", newSolution1.GetAnalyzerConfigDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString());
// Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028
var newSolution2 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity);
Assert.NotSame(newSolution1, newSolution2);
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity));
Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, (PreservationMode)(-1)));
Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity));
Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity));
}
[Fact]
public void WithProjectAssemblyName()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var assemblyName = "\0<>a/b/*.dll";
var newSolution = solution.WithProjectAssemblyName(projectId, assemblyName);
Assert.Equal(assemblyName, newSolution.GetProject(projectId)!.AssemblyName);
Assert.Same(newSolution, newSolution.WithProjectAssemblyName(projectId, assemblyName));
Assert.Throws<ArgumentNullException>("assemblyName", () => solution.WithProjectAssemblyName(projectId, null!));
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAssemblyName(null!, "x.dll"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectAssemblyName(ProjectId.CreateNewId(), "x.dll"));
}
[Fact]
public void WithProjectOutputFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.dll";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectOutputFilePath(projectId, value),
s => s.GetProject(projectId)!.OutputFilePath,
(string?)path,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputFilePath(null!, "x.dll"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputFilePath(ProjectId.CreateNewId(), "x.dll"));
}
[Fact]
public void WithProjectOutputRefFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.dll";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectOutputRefFilePath(projectId, value),
s => s.GetProject(projectId)!.OutputRefFilePath,
(string?)path,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputRefFilePath(null!, "x.dll"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputRefFilePath(ProjectId.CreateNewId(), "x.dll"));
}
[Fact]
public void WithProjectCompilationOutputInfo()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.dll";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectCompilationOutputInfo(projectId, value),
s => s.GetProject(projectId)!.CompilationOutputInfo,
new CompilationOutputInfo(path),
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOutputInfo(null!, new CompilationOutputInfo("x.dll")));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOutputInfo(ProjectId.CreateNewId(), new CompilationOutputInfo("x.dll")));
}
[Fact]
public void WithProjectDefaultNamespace()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var defaultNamespace = "\0<>a/b/*";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectDefaultNamespace(projectId, value),
s => s.GetProject(projectId)!.DefaultNamespace,
(string?)defaultNamespace,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectDefaultNamespace(null!, "x"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectDefaultNamespace(ProjectId.CreateNewId(), "x"));
}
[Fact]
public void WithProjectName()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var projectName = "\0<>a/b/*";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectName(projectId, value),
s => s.GetProject(projectId)!.Name,
projectName,
defaultThrows: true);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectName(null!, "x"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectName(ProjectId.CreateNewId(), "x"));
}
[Fact]
public void WithProjectFilePath()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
// any character is allowed
var path = "\0<>a/b/*.csproj";
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectFilePath(projectId, value),
s => s.GetProject(projectId)!.FilePath,
(string?)path,
defaultThrows: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectFilePath(null!, "x"));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectFilePath(ProjectId.CreateNewId(), "x"));
}
[Fact]
public void WithProjectCompilationOptionsExceptionHandling()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
var options = new CSharpCompilationOptions(OutputKind.NetModule);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOptions(null!, options));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOptions(ProjectId.CreateNewId(), options));
}
[Theory]
[CombinatorialData]
public void WithProjectCompilationOptionsReplacesSyntaxTreeOptionProvider([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName)
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", languageName);
// We always have a non-null SyntaxTreeOptionsProvider for C# and VB projects
var originalSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider;
Assert.NotNull(originalSyntaxTreeOptionsProvider);
var defaultOptions = solution.Projects.Single().LanguageServices.GetRequiredService<ICompilationFactoryService>().GetDefaultCompilationOptions();
Assert.Null(defaultOptions.SyntaxTreeOptionsProvider);
solution = solution.WithProjectCompilationOptions(projectId, defaultOptions);
// The CompilationOptions we replaced with didn't have a SyntaxTreeOptionsProvider, but we would have placed it
// back. The SyntaxTreeOptionsProvider should behave the same as the prior one and thus should be equal.
var newSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider;
Assert.NotNull(newSyntaxTreeOptionsProvider);
Assert.Equal(originalSyntaxTreeOptionsProvider, newSyntaxTreeOptionsProvider);
}
[Fact]
public void WithProjectParseOptions()
{
var projectId = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp);
var options = new CSharpParseOptions(CS.LanguageVersion.CSharp1);
SolutionTestHelpers.TestProperty(
solution,
(s, value) => s.WithProjectParseOptions(projectId, value),
s => s.GetProject(projectId)!.ParseOptions!,
(ParseOptions)options,
defaultThrows: true);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectParseOptions(null!, options));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectParseOptions(ProjectId.CreateNewId(), options));
}
[Fact]
public void WithProjectReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var projectId2 = ProjectId.CreateNewId();
solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp);
var projectRef = new ProjectReference(projectId2);
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithProjectReferences(projectId, value),
opt => opt.GetProject(projectId)!.AllProjectReferences,
projectRef,
allowDuplicates: false);
var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(
new ProjectReference(projectId2),
new ProjectReference(projectId2, ImmutableArray.Create("alias")),
new ProjectReference(projectId2, embedInteropTypes: true));
var solution2 = solution.WithProjectReferences(projectId, projectRefs);
Assert.Same(projectRefs, solution2.GetProject(projectId)!.AllProjectReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectReferences(null!, new[] { projectRef }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(ProjectId.CreateNewId(), new[] { projectRef }));
// cycles:
Assert.Throws<InvalidOperationException>(() => solution2.WithProjectReferences(projectId2, new[] { new ProjectReference(projectId) }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId, new[] { new ProjectReference(projectId) }));
}
[Fact]
[WorkItem(42406, "https://github.com/dotnet/roslyn/issues/42406")]
public void WithProjectReferences_ProjectNotInSolution()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var externalProjectRef = new ProjectReference(ProjectId.CreateNewId());
var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(externalProjectRef);
var newSolution1 = solution.WithProjectReferences(projectId, projectRefs);
Assert.Same(projectRefs, newSolution1.GetProject(projectId)!.AllProjectReferences);
// project reference is not included:
Assert.Empty(newSolution1.GetProject(projectId)!.ProjectReferences);
}
[Fact]
public void AddProjectReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
solution = solution
.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp)
.AddProject(projectId3, "proj3", "proj3.dll", LanguageNames.CSharp);
var projectRef2 = new ProjectReference(projectId2);
var projectRef3 = new ProjectReference(projectId3);
var externalProjectRef = new ProjectReference(ProjectId.CreateNewId());
solution = solution.AddProjectReference(projectId3, projectRef2);
var solution2 = solution.AddProjectReferences(projectId, EmptyEnumerable<ProjectReference>());
Assert.Same(solution, solution2);
var e = OnceEnumerable(projectRef2, externalProjectRef);
var solution3 = solution.AddProjectReferences(projectId, e);
AssertEx.Equal(new[] { projectRef2 }, solution3.GetProject(projectId)!.ProjectReferences);
AssertEx.Equal(new[] { projectRef2, externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.AddProjectReferences(null!, new[] { projectRef2 }));
Assert.Throws<ArgumentNullException>("projectReferences", () => solution.AddProjectReferences(projectId, null!));
Assert.Throws<ArgumentNullException>("projectReferences[0]", () => solution.AddProjectReferences(projectId, new ProjectReference[] { null! }));
Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { projectRef2, projectRef2 }));
Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { new ProjectReference(projectId2), new ProjectReference(projectId2) }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId3, new[] { projectRef2 }));
// cycles:
Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId2, new[] { projectRef3 }));
Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId, new[] { new ProjectReference(projectId) }));
}
[Fact]
public void RemoveProjectReference()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var projectId2 = ProjectId.CreateNewId();
solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp);
var projectRef2 = new ProjectReference(projectId2);
var externalProjectRef = new ProjectReference(ProjectId.CreateNewId());
solution = solution.WithProjectReferences(projectId, new[] { projectRef2, externalProjectRef });
// remove reference to a project that's not part of the solution:
var solution2 = solution.RemoveProjectReference(projectId, externalProjectRef);
AssertEx.Equal(new[] { projectRef2 }, solution2.GetProject(projectId)!.AllProjectReferences);
// remove reference to a project that's part of the solution:
var solution3 = solution.RemoveProjectReference(projectId, projectRef2);
AssertEx.Equal(new[] { externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences);
var solution4 = solution3.RemoveProjectReference(projectId, externalProjectRef);
Assert.Empty(solution4.GetProject(projectId)!.AllProjectReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveProjectReference(null!, projectRef2));
Assert.Throws<ArgumentNullException>("projectReference", () => solution.RemoveProjectReference(projectId, null!));
// removing a reference that's not in the list:
Assert.Throws<ArgumentException>("projectReference", () => solution.RemoveProjectReference(projectId, new ProjectReference(ProjectId.CreateNewId())));
// project not in solution:
Assert.Throws<InvalidOperationException>(() => solution.RemoveProjectReference(ProjectId.CreateNewId(), projectRef2));
}
[Fact]
public void ProjectReferences_Submissions()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId0 = ProjectId.CreateNewId();
var submissionId1 = ProjectId.CreateNewId();
var submissionId2 = ProjectId.CreateNewId();
var submissionId3 = ProjectId.CreateNewId();
solution = solution
.AddProject(projectId0, "non-submission", "non-submission.dll", LanguageNames.CSharp)
.AddProject(ProjectInfo.Create(submissionId1, VersionStamp.Default, name: "submission1", assemblyName: "submission1.dll", LanguageNames.CSharp, isSubmission: true))
.AddProject(ProjectInfo.Create(submissionId2, VersionStamp.Default, name: "submission2", assemblyName: "submission2.dll", LanguageNames.CSharp, isSubmission: true))
.AddProject(ProjectInfo.Create(submissionId3, VersionStamp.Default, name: "submission3", assemblyName: "submission3.dll", LanguageNames.CSharp, isSubmission: true))
.AddProjectReference(submissionId2, new ProjectReference(submissionId1))
.WithProjectReferences(submissionId2, new[] { new ProjectReference(submissionId1) });
// submission may be referenced from multiple submissions (forming a tree):
_ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) });
_ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) });
// submission may reference a non-submission project:
_ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) });
_ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) });
// submission can't reference multiple submissions:
Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(submissionId2, new[] { new ProjectReference(submissionId3) }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(submissionId1, new[] { new ProjectReference(submissionId2), new ProjectReference(submissionId3) }));
// non-submission project can't reference a submission:
Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) }));
}
[Fact]
public void WithProjectMetadataReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var metadataRef = (MetadataReference)new TestMetadataReference();
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithProjectMetadataReferences(projectId, value),
opt => opt.GetProject(projectId)!.MetadataReferences,
metadataRef,
allowDuplicates: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectMetadataReferences(null!, new[] { metadataRef }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectMetadataReferences(ProjectId.CreateNewId(), new[] { metadataRef }));
}
[Fact]
public void AddMetadataReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var solution2 = solution.AddMetadataReferences(projectId, EmptyEnumerable<MetadataReference>());
Assert.Same(solution, solution2);
var metadataRef1 = new TestMetadataReference();
var metadataRef2 = new TestMetadataReference();
var solution3 = solution.AddMetadataReferences(projectId, OnceEnumerable(metadataRef1, metadataRef2));
AssertEx.Equal(new[] { metadataRef1, metadataRef2 }, solution3.GetProject(projectId)!.MetadataReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.AddMetadataReferences(null!, new[] { metadataRef1 }));
Assert.Throws<ArgumentNullException>("metadataReferences", () => solution.AddMetadataReferences(projectId, null!));
Assert.Throws<ArgumentNullException>("metadataReferences[0]", () => solution.AddMetadataReferences(projectId, new MetadataReference[] { null! }));
Assert.Throws<ArgumentException>("metadataReferences[1]", () => solution.AddMetadataReferences(projectId, new[] { metadataRef1, metadataRef1 }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution3.AddMetadataReferences(projectId, new[] { metadataRef1 }));
}
[Fact]
public void RemoveMetadataReference()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var metadataRef1 = new TestMetadataReference();
var metadataRef2 = new TestMetadataReference();
solution = solution.WithProjectMetadataReferences(projectId, new[] { metadataRef1, metadataRef2 });
var solution2 = solution.RemoveMetadataReference(projectId, metadataRef1);
AssertEx.Equal(new[] { metadataRef2 }, solution2.GetProject(projectId)!.MetadataReferences);
var solution3 = solution2.RemoveMetadataReference(projectId, metadataRef2);
Assert.Empty(solution3.GetProject(projectId)!.MetadataReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveMetadataReference(null!, metadataRef1));
Assert.Throws<ArgumentNullException>("metadataReference", () => solution.RemoveMetadataReference(projectId, null!));
// removing a reference that's not in the list:
Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(projectId, new TestMetadataReference()));
// project not in solution:
Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(ProjectId.CreateNewId(), metadataRef1));
}
[Fact]
public void WithProjectAnalyzerReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var analyzerRef = (AnalyzerReference)new TestAnalyzerReference();
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithProjectAnalyzerReferences(projectId, value),
opt => opt.GetProject(projectId)!.AnalyzerReferences,
analyzerRef,
allowDuplicates: false);
Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAnalyzerReferences(null!, new[] { analyzerRef }));
Assert.Throws<InvalidOperationException>(() => solution.WithProjectAnalyzerReferences(ProjectId.CreateNewId(), new[] { analyzerRef }));
}
[Fact]
public void AddAnalyzerReferences_Project()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var solution2 = solution.AddAnalyzerReferences(projectId, EmptyEnumerable<AnalyzerReference>());
Assert.Same(solution, solution2);
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
var solution3 = solution.AddAnalyzerReferences(projectId, OnceEnumerable(analyzerRef1, analyzerRef2));
AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.GetProject(projectId)!.AnalyzerReferences);
var solution4 = solution3.AddAnalyzerReferences(projectId, new AnalyzerReference[0]);
Assert.Same(solution, solution2);
Assert.Throws<ArgumentNullException>("projectId", () => solution.AddAnalyzerReferences(null!, new[] { analyzerRef1 }));
Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(projectId, null!));
Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(projectId, new AnalyzerReference[] { null! }));
Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef1 }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(projectId, new[] { analyzerRef1 }));
}
[Fact]
public void RemoveAnalyzerReference_Project()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var projectId = solution.Projects.Single().Id;
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
solution = solution.WithProjectAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef2 });
var solution2 = solution.RemoveAnalyzerReference(projectId, analyzerRef1);
AssertEx.Equal(new[] { analyzerRef2 }, solution2.GetProject(projectId)!.AnalyzerReferences);
var solution3 = solution2.RemoveAnalyzerReference(projectId, analyzerRef2);
Assert.Empty(solution3.GetProject(projectId)!.AnalyzerReferences);
Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveAnalyzerReference(null!, analyzerRef1));
Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(projectId, null!));
// removing a reference that's not in the list:
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(projectId, new TestAnalyzerReference()));
// project not in solution:
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(ProjectId.CreateNewId(), analyzerRef1));
}
[Fact]
public void WithAnalyzerReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var analyzerRef = (AnalyzerReference)new TestAnalyzerReference();
SolutionTestHelpers.TestListProperty(solution,
(old, value) => old.WithAnalyzerReferences(value),
opt => opt.AnalyzerReferences,
analyzerRef,
allowDuplicates: false);
}
[Fact]
public void AddAnalyzerReferences()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var solution2 = solution.AddAnalyzerReferences(EmptyEnumerable<AnalyzerReference>());
Assert.Same(solution, solution2);
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
var solution3 = solution.AddAnalyzerReferences(OnceEnumerable(analyzerRef1, analyzerRef2));
AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.AnalyzerReferences);
var solution4 = solution3.AddAnalyzerReferences(new AnalyzerReference[0]);
Assert.Same(solution, solution2);
Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(null!));
Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(new AnalyzerReference[] { null! }));
Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(new[] { analyzerRef1, analyzerRef1 }));
// dup:
Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(new[] { analyzerRef1 }));
}
[Fact]
public void RemoveAnalyzerReference()
{
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var analyzerRef1 = new TestAnalyzerReference();
var analyzerRef2 = new TestAnalyzerReference();
solution = solution.WithAnalyzerReferences(new[] { analyzerRef1, analyzerRef2 });
var solution2 = solution.RemoveAnalyzerReference(analyzerRef1);
AssertEx.Equal(new[] { analyzerRef2 }, solution2.AnalyzerReferences);
var solution3 = solution2.RemoveAnalyzerReference(analyzerRef2);
Assert.Empty(solution3.AnalyzerReferences);
Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(null!));
// removing a reference that's not in the list:
Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(new TestAnalyzerReference()));
}
#nullable disable
[Fact]
public void TestAddProject()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
solution = solution.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp);
Assert.True(solution.ProjectIds.Any(), "Solution was expected to have projects");
Assert.NotNull(pid);
var project = solution.GetProject(pid);
Assert.False(project.HasDocuments);
}
[Fact]
public void TestUpdateAssemblyName()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
solution = solution.WithProjectAssemblyName(project1, "bar");
var project = solution.GetProject(project1);
Assert.Equal("bar", project.AssemblyName);
}
[Fact]
[WorkItem(543964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543964")]
public void MultipleProjectsWithSameDisplayName()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
var project2 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "name", "assemblyName", LanguageNames.CSharp);
solution = solution.AddProject(project2, "name", "assemblyName", LanguageNames.CSharp);
Assert.Equal(2, solution.GetProjectsByName("name").Count());
}
[Fact]
public async Task TestAddFirstDocumentAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", "public class Goo { }");
// verify project & document
Assert.NotNull(pid);
var project = solution.GetProject(pid);
Assert.NotNull(project);
Assert.True(solution.ContainsProject(pid), "Solution was expected to have project " + pid);
Assert.True(project.HasDocuments, "Project was expected to have documents");
Assert.Equal(project, solution.GetProject(pid));
Assert.NotNull(did);
var document = solution.GetDocument(did);
Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did);
Assert.Equal(document, project.GetDocument(did));
Assert.Equal(document, solution.GetDocument(did));
var semantics = await document.GetSemanticModelAsync();
Assert.NotNull(semantics);
await ValidateSolutionAndCompilationsAsync(solution);
var pid2 = solution.Projects.Single().Id;
var did2 = DocumentId.CreateNewId(pid2);
solution = solution.AddDocument(did2, "bar.cs", "public class Bar { }");
// verify project & document
var project2 = solution.GetProject(pid2);
Assert.NotNull(project2);
Assert.NotNull(did2);
var document2 = solution.GetDocument(did2);
Assert.True(project2.ContainsDocument(did2), "Project was expected to have document " + did2);
Assert.Equal(document2, project2.GetDocument(did2));
Assert.Equal(document2, solution.GetDocument(did2));
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task AddTwoDocumentsForSingleProject()
{
var projectId = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
var project = Assert.Single(solution.Projects);
var document1 = project.GetDocument(documentInfo1.Id);
var document2 = project.GetDocument(documentInfo2.Id);
Assert.NotSame(document1, document2);
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task AddTwoDocumentsForTwoProjects()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
var project1 = solution.GetProject(projectId1);
var project2 = solution.GetProject(projectId2);
var document1 = project1.GetDocument(documentInfo1.Id);
var document2 = project2.GetDocument(documentInfo2.Id);
Assert.NotSame(document1, document2);
Assert.NotSame(document1.Project, document2.Project);
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public void AddTwoDocumentsWithMissingProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs");
// We're only adding the first project, but not the second one
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp);
Assert.ThrowsAny<InvalidOperationException>(() => solution.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)));
}
[Fact]
public void RemoveZeroDocuments()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
Assert.Same(solution, solution.RemoveDocuments(ImmutableArray<DocumentId>.Empty));
}
[Fact]
public async Task RemoveTwoDocuments()
{
var projectId = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "project1", "project1.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id));
var finalProject = solution.Projects.Single();
Assert.Empty(finalProject.Documents);
Assert.Empty((await finalProject.GetCompilationAsync()).SyntaxTrees);
}
[Fact]
public void RemoveTwoDocumentsFromDifferentProjects()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2));
Assert.All(solution.Projects, p => Assert.Single(p.Documents));
solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id));
Assert.All(solution.Projects, p => Assert.Empty(p.Documents));
}
[Fact]
public void RemoveDocumentFromUnrelatedProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddDocument(documentInfo1);
// This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveDocument
// API due to https://github.com/dotnet/roslyn/issues/41211.
Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveDocuments(ImmutableArray.Create(documentInfo1.Id)));
}
[Fact]
public void RemoveAdditionalDocumentFromUnrelatedProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.txt");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddAdditionalDocument(documentInfo1);
// This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument
// API due to https://github.com/dotnet/roslyn/issues/41211.
Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAdditionalDocuments(ImmutableArray.Create(documentInfo1.Id)));
}
[Fact]
public void RemoveAnalyzerConfigDocumentFromUnrelatedProject()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), ".editorconfig");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp)
.AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp)
.AddAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1));
// This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument
// API due to https://github.com/dotnet/roslyn/issues/41211.
Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1.Id)));
}
[Fact]
public async Task TestOneCSharpProjectAsync()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject("goo", "goo.dll", LanguageNames.CSharp)
.AddMetadataReference(s_mscorlib)
.AddDocument("goo.cs", "public class Goo { }")
.Project.Solution;
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task TestTwoCSharpProjectsAsync()
{
using var workspace = CreateWorkspace();
var pm1 = ProjectId.CreateNewId();
var pm2 = ProjectId.CreateNewId();
var doc1 = DocumentId.CreateNewId(pm1);
var doc2 = DocumentId.CreateNewId(pm2);
var solution = workspace.CurrentSolution
.AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp)
.AddProject(pm2, "bar", "bar.dll", LanguageNames.CSharp)
.AddProjectReference(pm2, new ProjectReference(pm1))
.AddDocument(doc1, "goo.cs", "public class Goo { }")
.AddDocument(doc2, "bar.cs", "public class Bar : Goo { }");
await ValidateSolutionAndCompilationsAsync(solution);
}
[Fact]
public async Task TestCrossLanguageProjectsAsync()
{
var pm1 = ProjectId.CreateNewId();
var pm2 = ProjectId.CreateNewId();
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp)
.AddMetadataReference(pm1, s_mscorlib)
.AddProject(pm2, "bar", "bar.dll", LanguageNames.VisualBasic)
.AddMetadataReference(pm2, s_mscorlib)
.AddProjectReference(pm2, new ProjectReference(pm1))
.AddDocument(DocumentId.CreateNewId(pm1), "goo.cs", "public class X { }")
.AddDocument(DocumentId.CreateNewId(pm2), "bar.vb", "Public Class Y\r\nInherits X\r\nEnd Class");
await ValidateSolutionAndCompilationsAsync(solution);
}
private static async Task ValidateSolutionAndCompilationsAsync(Solution solution)
{
foreach (var project in solution.Projects)
{
Assert.True(solution.ContainsProject(project.Id), "Solution was expected to have project " + project.Id);
Assert.Equal(project, solution.GetProject(project.Id));
// these won't always be unique in real-world but should be for these tests
Assert.Equal(project, solution.GetProjectsByName(project.Name).FirstOrDefault());
var compilation = await project.GetCompilationAsync();
Assert.NotNull(compilation);
// check that the options are the same
Assert.Equal(project.CompilationOptions, compilation.Options);
// check that all known metadata references are present in the compilation
foreach (var meta in project.MetadataReferences)
{
Assert.True(compilation.References.Contains(meta), "Compilation references were expected to contain " + meta);
}
// check that all project-to-project reference metadata is present in the compilation
foreach (var referenced in project.ProjectReferences)
{
if (solution.ContainsProject(referenced.ProjectId))
{
var referencedMetadata = await solution.State.GetMetadataReferenceAsync(referenced, solution.GetProjectState(project.Id), CancellationToken.None);
Assert.NotNull(referencedMetadata);
if (referencedMetadata is CompilationReference compilationReference)
{
compilation.References.Single(r =>
{
var cr = r as CompilationReference;
return cr != null && cr.Compilation == compilationReference.Compilation;
});
}
}
}
// check that the syntax trees are the same
var docs = project.Documents.ToList();
var trees = compilation.SyntaxTrees.ToList();
Assert.Equal(docs.Count, trees.Count);
foreach (var doc in docs)
{
Assert.True(trees.Contains(await doc.GetSyntaxTreeAsync()), "trees list was expected to contain the syntax tree of doc");
}
}
}
#if false
[Fact(Skip = "641963")]
public void TestDeepProjectReferenceTree()
{
int projectCount = 5;
var solution = CreateSolutionWithProjectDependencyChain(projectCount);
ProjectId[] projectIds = solution.ProjectIds.ToArray();
Compilation compilation;
for (int i = 0; i < projectCount; i++)
{
Assert.False(solution.GetProject(projectIds[i]).TryGetCompilation(out compilation));
}
var top = solution.GetCompilationAsync(projectIds.Last(), CancellationToken.None).Result;
var partialSolution = solution.GetPartialSolution();
for (int i = 0; i < projectCount; i++)
{
// While holding a compilation, we also hold its references, plus one further level
// of references alive. However, the references are only partial Declaration
// compilations
var isPartialAvailable = i >= projectCount - 3;
var isFinalAvailable = i == projectCount - 1;
var projectId = projectIds[i];
Assert.Equal(isFinalAvailable, solution.GetProject(projectId).TryGetCompilation(out compilation));
Assert.Equal(isPartialAvailable, partialSolution.ProjectIds.Contains(projectId) && partialSolution.GetProject(projectId).TryGetCompilation(out compilation));
}
}
#endif
[WorkItem(636431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636431")]
[Fact]
public async Task TestProjectDependencyLoadingAsync()
{
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var solution = workspace.CurrentSolution;
var projectIds = Enumerable.Range(0, 5).Select(i => ProjectId.CreateNewId()).ToArray();
for (var i = 0; i < projectIds.Length; i++)
{
solution = solution.AddProject(projectIds[i], i.ToString(), i.ToString(), LanguageNames.CSharp);
if (i >= 1)
{
solution = solution.AddProjectReference(projectIds[i], new ProjectReference(projectIds[i - 1]));
}
}
await solution.GetProject(projectIds[0]).GetCompilationAsync(CancellationToken.None);
await solution.GetProject(projectIds[2]).GetCompilationAsync(CancellationToken.None);
}
[Fact]
public async Task TestAddMetadataReferencesAsync()
{
var mefReference = TestMetadata.Net451.SystemCore;
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
solution = solution.AddMetadataReference(project1, s_mscorlib);
solution = solution.AddMetadataReference(project1, mefReference);
var assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference);
var namespacesAndTypes = assemblyReference.GlobalNamespace.GetAllNamespacesAndTypes(CancellationToken.None);
var foundSymbol = from symbol in namespacesAndTypes
where symbol.Name.Equals("Enumerable")
select symbol;
Assert.Equal(1, foundSymbol.Count());
solution = solution.RemoveMetadataReference(project1, mefReference);
assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference);
Assert.Null(assemblyReference);
await ValidateSolutionAndCompilationsAsync(solution);
}
private class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
public override void Initialize(AnalysisContext analysisContext)
{
}
}
[Fact]
public void TestProjectDiagnosticAnalyzers()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
Assert.Empty(solution.Projects.Single().AnalyzerReferences);
DiagnosticAnalyzer analyzer = new MockDiagnosticAnalyzer();
var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer));
// Test AddAnalyzer
var newSolution = solution.AddAnalyzerReference(project1, analyzerReference);
var actualAnalyzerReferences = newSolution.Projects.Single().AnalyzerReferences;
Assert.Equal(1, actualAnalyzerReferences.Count);
Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
var actualAnalyzers = actualAnalyzerReferences[0].GetAnalyzersForAllLanguages();
Assert.Equal(1, actualAnalyzers.Length);
Assert.Equal(analyzer, actualAnalyzers[0]);
// Test ProjectChanges
var changes = newSolution.GetChanges(solution).GetProjectChanges().Single();
var addedAnalyzerReference = changes.GetAddedAnalyzerReferences().Single();
Assert.Equal(analyzerReference, addedAnalyzerReference);
var removedAnalyzerReferences = changes.GetRemovedAnalyzerReferences();
Assert.Empty(removedAnalyzerReferences);
solution = newSolution;
// Test RemoveAnalyzer
solution = solution.RemoveAnalyzerReference(project1, analyzerReference);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Empty(actualAnalyzerReferences);
// Test AddAnalyzers
analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer));
DiagnosticAnalyzer secondAnalyzer = new MockDiagnosticAnalyzer();
var secondAnalyzerReference = new AnalyzerImageReference(ImmutableArray.Create(secondAnalyzer));
var analyzerReferences = new[] { analyzerReference, secondAnalyzerReference };
solution = solution.AddAnalyzerReferences(project1, analyzerReferences);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Equal(2, actualAnalyzerReferences.Count);
Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]);
solution = solution.RemoveAnalyzerReference(project1, analyzerReference);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Equal(1, actualAnalyzerReferences.Count);
Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[0]);
// Test WithAnalyzers
solution = solution.WithProjectAnalyzerReferences(project1, analyzerReferences);
actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
Assert.Equal(2, actualAnalyzerReferences.Count);
Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]);
}
[Fact]
public void TestProjectParseOptions()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project1 = ProjectId.CreateNewId();
solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp);
solution = solution.AddMetadataReference(project1, s_mscorlib);
// Parse Options
var oldParseOptions = solution.GetProject(project1).ParseOptions;
var newParseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "AFTER" });
solution = solution.WithProjectParseOptions(project1, newParseOptions);
var newUpdatedParseOptions = solution.GetProject(project1).ParseOptions;
Assert.NotEqual(oldParseOptions, newUpdatedParseOptions);
Assert.Same(newParseOptions, newUpdatedParseOptions);
}
[Fact]
public async Task TestRemoveProjectAsync()
{
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp);
Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects");
Assert.NotNull(pid);
var project = sol.GetProject(pid);
Assert.False(project.HasDocuments);
var sol2 = sol.RemoveProject(pid);
Assert.False(sol2.ProjectIds.Any());
await ValidateSolutionAndCompilationsAsync(sol);
}
[Fact]
public async Task TestRemoveProjectWithReferencesAsync()
{
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
var pid2 = ProjectId.CreateNewId();
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp)
.AddProjectReference(pid2, new ProjectReference(pid));
Assert.Equal(2, sol.Projects.Count());
// remove the project that is being referenced
// this should leave a dangling reference
var sol2 = sol.RemoveProject(pid);
Assert.False(sol2.ContainsProject(pid));
Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2);
Assert.Equal(1, sol2.Projects.Count());
Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 project pid2 was expected to contain project reference " + pid);
await ValidateSolutionAndCompilationsAsync(sol2);
}
[Fact]
public async Task TestRemoveProjectWithReferencesAndAddItBackAsync()
{
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
var pid2 = ProjectId.CreateNewId();
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp)
.AddProjectReference(pid2, new ProjectReference(pid));
Assert.Equal(2, sol.Projects.Count());
// remove the project that is being referenced
var sol2 = sol.RemoveProject(pid);
Assert.False(sol2.ContainsProject(pid));
Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2);
Assert.Equal(1, sol2.Projects.Count());
Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 pid2 was expected to contain " + pid);
var sol3 = sol2.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp);
Assert.True(sol3.ContainsProject(pid), "sol3 was expected to contain " + pid);
Assert.True(sol3.ContainsProject(pid2), "sol3 was expected to contain " + pid2);
Assert.Equal(2, sol3.Projects.Count());
await ValidateSolutionAndCompilationsAsync(sol3);
}
[Fact]
public async Task TestGetSyntaxRootAsync()
{
var text = "public class Goo { }";
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var document = sol.GetDocument(did);
Assert.False(document.TryGetSyntaxRoot(out _));
var root = await document.GetSyntaxRootAsync();
Assert.NotNull(root);
Assert.Equal(text, root.ToString());
Assert.True(document.TryGetSyntaxRoot(out root));
Assert.NotNull(root);
}
[Fact]
public async Task TestUpdateDocumentAsync()
{
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
using var workspace = CreateWorkspace();
var solution1 = workspace.CurrentSolution
.AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp)
.AddDocument(documentId, "DocumentName", SourceText.From("class Class{}"));
var document = solution1.GetDocument(documentId);
var newRoot = await Formatter.FormatAsync(document).Result.GetSyntaxRootAsync();
var solution2 = solution1.WithDocumentSyntaxRoot(documentId, newRoot);
Assert.NotEqual(solution1, solution2);
var newText = solution2.GetDocument(documentId).GetTextAsync().Result.ToString();
Assert.Equal("class Class { }", newText);
}
[Fact]
public void TestUpdateSyntaxTreeWithAnnotations()
{
var text = "public class Goo { }";
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var document = sol.GetDocument(did);
var tree = document.GetSyntaxTreeAsync().Result;
var root = tree.GetRoot();
var annotation = new SyntaxAnnotation();
var annotatedRoot = root.WithAdditionalAnnotations(annotation);
var sol2 = sol.WithDocumentSyntaxRoot(did, annotatedRoot);
var doc2 = sol2.GetDocument(did);
var tree2 = doc2.GetSyntaxTreeAsync().Result;
var root2 = tree2.GetRoot();
// text should not be available yet (it should be defer created from the node)
// and getting the document or root should not cause it to be created.
Assert.False(tree2.TryGetText(out _));
var text2 = tree2.GetText();
Assert.NotNull(text2);
Assert.NotSame(tree, tree2);
Assert.NotSame(annotatedRoot, root2);
Assert.True(annotatedRoot.IsEquivalentTo(root2));
Assert.True(root2.HasAnnotation(annotation));
}
[Fact]
public void TestUpdatingFilePathUpdatesSyntaxTree()
{
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
const string OldFilePath = @"Z:\OldFilePath.cs";
const string NewFilePath = @"Z:\NewFilePath.cs";
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(documentId, "OldFilePath.cs", "public class Goo { }", filePath: OldFilePath);
// scope so later asserts don't accidentally use oldDocument
{
var oldDocument = solution.GetDocument(documentId);
Assert.Equal(OldFilePath, oldDocument.FilePath);
Assert.Equal(OldFilePath, oldDocument.GetSyntaxTreeAsync().Result.FilePath);
}
solution = solution.WithDocumentFilePath(documentId, NewFilePath);
{
var newDocument = solution.GetDocument(documentId);
Assert.Equal(NewFilePath, newDocument.FilePath);
Assert.Equal(NewFilePath, newDocument.GetSyntaxTreeAsync().Result.FilePath);
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestSyntaxRootNotKeptAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", "public class Goo { }");
var observedRoot = GetObservedSyntaxTreeRoot(sol, did);
observedRoot.AssertReleased();
// re-get the tree (should recover from storage, not reparse)
_ = sol.GetDocument(did).GetSyntaxRootAsync().Result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact]
[WorkItem(542736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542736")]
public void TestDocumentChangedOnDiskIsNotObserved()
{
var text1 = "public class A {}";
var text2 = "public class B {}";
var file = Temp.CreateFile().WriteAllText(text1, Encoding.UTF8);
// create a solution that evicts from the cache immediately.
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
var observedText = GetObservedText(sol, did, text1);
// change text on disk & verify it is changed
file.WriteAllText(text2);
var textOnDisk = file.ReadAllText();
Assert.Equal(text2, textOnDisk);
// stop observing it and let GC reclaim it
observedText.AssertReleased();
// if we ask for the same text again we should get the original content
var observedText2 = sol.GetDocument(did).GetTextAsync().Result;
Assert.Equal(text1, observedText2.ToString());
}
[Fact]
public void TestGetTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docText = doc.GetTextAsync().Result;
Assert.NotNull(docText);
Assert.Equal(text, docText.ToString());
}
[Fact]
public void TestGetLoadedTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
var doc = sol.GetDocument(did);
var docText = doc.GetTextAsync().Result;
Assert.NotNull(docText);
Assert.Equal(text, docText.ToString());
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/19427")]
public void TestGetRecoveredTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the text and then wait for the references to be GC'd
var observed = GetObservedText(sol, did, text);
observed.AssertReleased();
// get it async and force it to recover from temporary storage
var doc = sol.GetDocument(did);
var docText = doc.GetTextAsync().Result;
Assert.NotNull(docText);
Assert.Equal(text, docText.ToString());
}
[Fact]
public void TestGetSyntaxTreeAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docTree = doc.GetSyntaxTreeAsync().Result;
Assert.NotNull(docTree);
Assert.Equal(text, docTree.GetRoot().ToString());
}
[Fact]
public void TestGetSyntaxTreeFromLoadedTextAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8);
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
var doc = sol.GetDocument(did);
var docTree = doc.GetSyntaxTreeAsync().Result;
Assert.NotNull(docTree);
Assert.Equal(text, docTree.GetRoot().ToString());
}
[Fact]
public void TestGetSyntaxTreeFromAddedTree()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var tree = CSharp.SyntaxFactory.ParseSyntaxTree("public class C {}").GetRoot(CancellationToken.None);
tree = tree.WithAdditionalAnnotations(new SyntaxAnnotation("test"));
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "x", tree);
var doc = sol.GetDocument(did);
var docTree = doc.GetSyntaxRootAsync().Result;
Assert.NotNull(docTree);
Assert.True(tree.IsEquivalentTo(docTree));
Assert.NotNull(docTree.GetAnnotatedNodes("test").Single());
}
[Fact]
public async Task TestGetSyntaxRootAsync2Async()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docRoot = await doc.GetSyntaxRootAsync();
Assert.NotNull(docRoot);
Assert.Equal(text, docRoot.ToString());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/14954")]
public void TestGetRecoveredSyntaxRootAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the syntax tree root and wait for the references to be GC'd
var observed = GetObservedSyntaxTreeRoot(sol, did);
observed.AssertReleased();
// get it async and force it to be recovered from storage
var doc = sol.GetDocument(did);
var docRoot = doc.GetSyntaxRootAsync().Result;
Assert.NotNull(docRoot);
Assert.Equal(text, docRoot.ToString());
}
[Fact]
public void TestGetCompilationAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var proj = sol.GetProject(pid);
var compilation = proj.GetCompilationAsync().Result;
Assert.NotNull(compilation);
Assert.Equal(1, compilation.SyntaxTrees.Count());
}
[Fact]
public void TestGetSemanticModelAsync()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspace();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
var doc = sol.GetDocument(did);
var docModel = doc.GetSemanticModelAsync().Result;
Assert.NotNull(docModel);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetTextDoesNotKeepTextAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the text and then wait for the references to be GC'd
var observed = GetObservedText(sol, did, text);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SourceText> GetObservedText(Solution solution, DocumentId documentId, string expectedText = null)
{
var observedText = solution.GetDocument(documentId).GetTextAsync().Result;
if (expectedText != null)
{
Assert.Equal(expectedText, observedText.ToString());
}
return new ObjectReference<SourceText>(observedText);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetTextAsyncDoesNotKeepTextAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// observe the text and then wait for the references to be GC'd
var observed = GetObservedTextAsync(sol, did, text);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SourceText> GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null)
{
var observedText = solution.GetDocument(documentId).GetTextAsync().Result;
if (expectedText != null)
{
Assert.Equal(expectedText, observedText.ToString());
}
return new ObjectReference<SourceText>(observedText);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetSyntaxRootDoesNotKeepRootAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedSyntaxTreeRoot(sol, did);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRoot(Solution solution, DocumentId documentId)
{
var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result;
return new ObjectReference<SyntaxNode>(observedTree);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetSyntaxRootAsyncDoesNotKeepRootAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedSyntaxTreeRootAsync(sol, did);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRootAsync(Solution solution, DocumentId documentId)
{
var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result;
return new ObjectReference<SyntaxNode>(observedTree);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13506")]
[WorkItem(13506, "https://github.com/dotnet/roslyn/issues/13506")]
public void TestRecoverableSyntaxTreeCSharp()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = @"public class C {
public void Method1() {}
public void Method2() {}
public void Method3() {}
public void Method4() {}
public void Method5() {}
public void Method6() {}
}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
TestRecoverableSyntaxTree(sol, did);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestRecoverableSyntaxTreeVisualBasic()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = @"Public Class C
Sub Method1()
End Sub
Sub Method2()
End Sub
Sub Method3()
End Sub
Sub Method4()
End Sub
Sub Method5()
End Sub
Sub Method6()
End Sub
End Class";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.VisualBasic)
.AddDocument(did, "goo.vb", text);
TestRecoverableSyntaxTree(sol, did);
}
private static void TestRecoverableSyntaxTree(Solution sol, DocumentId did)
{
// get it async and wait for it to get GC'd
var observed = GetObservedSyntaxTreeRootAsync(sol, did);
observed.AssertReleased();
var doc = sol.GetDocument(did);
// access the tree & root again (recover it)
var tree = doc.GetSyntaxTreeAsync().Result;
// this should cause reparsing
var root = tree.GetRoot();
// prove that the new root is correctly associated with the tree
Assert.Equal(tree, root.SyntaxTree);
// reset the syntax root, to make it 'refactored' by adding an attribute
var newRoot = doc.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation);
var doc2 = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot, PreservationMode.PreserveValue).GetDocument(doc.Id);
// get it async and wait for it to get GC'd
var observed2 = GetObservedSyntaxTreeRootAsync(doc2.Project.Solution, did);
observed2.AssertReleased();
// access the tree & root again (recover it)
var tree2 = doc2.GetSyntaxTreeAsync().Result;
// this should cause deserialization
var root2 = tree2.GetRoot();
// prove that the new root is correctly associated with the tree
Assert.Equal(tree2, root2.SyntaxTree);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetCompilationAsyncDoesNotKeepCompilationAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedCompilationAsync(sol, pid);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<Compilation> GetObservedCompilationAsync(Solution solution, ProjectId projectId)
{
var observed = solution.GetProject(projectId).GetCompilationAsync().Result;
return new ObjectReference<Compilation>(observed);
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")]
public void TestGetCompilationDoesNotKeepCompilationAlive()
{
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
var text = "public class C {}";
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var sol = workspace.CurrentSolution
.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp)
.AddDocument(did, "goo.cs", text);
// get it async and wait for it to get GC'd
var observed = GetObservedCompilation(sol, pid);
observed.AssertReleased();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static ObjectReference<Compilation> GetObservedCompilation(Solution solution, ProjectId projectId)
{
var observed = solution.GetProject(projectId).GetCompilationAsync().Result;
return new ObjectReference<Compilation>(observed);
}
[Fact]
public void TestWorkspaceLanguageServiceOverride()
{
var hostServices = FeaturesTestCompositions.Features.AddParts(new[]
{
typeof(TestLanguageServiceA),
typeof(TestLanguageServiceB),
}).GetHostServices();
var ws = new AdhocWorkspace(hostServices, ServiceLayer.Host);
var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
Assert.NotNull(service as TestLanguageServiceA);
var ws2 = new AdhocWorkspace(hostServices, "Quasimodo");
var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
Assert.NotNull(service2 as TestLanguageServiceB);
}
#if false
[Fact]
public void TestSolutionInfo()
{
var oldSolutionId = SolutionId.CreateNewId("oldId");
var oldVersion = VersionStamp.Create();
var solutionInfo = SolutionInfo.Create(oldSolutionId, oldVersion, null, null);
var newSolutionId = SolutionId.CreateNewId("newId");
solutionInfo = solutionInfo.WithId(newSolutionId);
Assert.NotEqual(oldSolutionId, solutionInfo.Id);
Assert.Equal(newSolutionId, solutionInfo.Id);
var newVersion = oldVersion.GetNewerVersion();
solutionInfo = solutionInfo.WithVersion(newVersion);
Assert.NotEqual(oldVersion, solutionInfo.Version);
Assert.Equal(newVersion, solutionInfo.Version);
Assert.Null(solutionInfo.FilePath);
var newFilePath = @"C:\test\fake.sln";
solutionInfo = solutionInfo.WithFilePath(newFilePath);
Assert.Equal(newFilePath, solutionInfo.FilePath);
Assert.Equal(0, solutionInfo.Projects.Count());
}
#endif
private interface ITestLanguageService : ILanguageService
{
}
[ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, ServiceLayer.Default), Shared, PartNotDiscoverable]
private class TestLanguageServiceA : ITestLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLanguageServiceA()
{
}
}
[ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, "Quasimodo"), Shared, PartNotDiscoverable]
private class TestLanguageServiceB : ITestLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLanguageServiceB()
{
}
}
[Fact]
[WorkItem(666263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666263")]
public async Task TestDocumentFileAccessFailureMissingFile()
{
var workspace = new AdhocWorkspace();
var solution = workspace.CurrentSolution;
WorkspaceDiagnostic diagnosticFromEvent = null;
solution.Workspace.WorkspaceFailed += (sender, args) =>
{
diagnosticFromEvent = args.Diagnostic;
};
var pid = ProjectId.CreateNewId();
var did = DocumentId.CreateNewId(pid);
solution = solution.AddProject(pid, "goo", "goo", LanguageNames.CSharp)
.AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8))
.WithDocumentFilePath(did, "document path");
var doc = solution.GetDocument(did);
var text = await doc.GetTextAsync().ConfigureAwait(false);
var diagnostic = await doc.State.GetLoadDiagnosticAsync(CancellationToken.None).ConfigureAwait(false);
Assert.Equal(@"C:\doesnotexist.cs: (0,0)-(0,0)", diagnostic.Location.GetLineSpan().ToString());
Assert.Equal(WorkspaceDiagnosticKind.Failure, diagnosticFromEvent.Kind);
Assert.Equal("", text.ToString());
// Verify invariant: The compilation is guaranteed to have a syntax tree for each document of the project (even if the contnet fails to load).
var compilation = await solution.State.GetCompilationAsync(doc.Project.State, CancellationToken.None).ConfigureAwait(false);
var syntaxTree = compilation.SyntaxTrees.Single();
Assert.Equal("", syntaxTree.ToString());
}
[Fact]
public void TestGetProjectForAssemblySymbol()
{
var pid1 = ProjectId.CreateNewId("p1");
var pid2 = ProjectId.CreateNewId("p2");
var pid3 = ProjectId.CreateNewId("p3");
var did1 = DocumentId.CreateNewId(pid1);
var did2 = DocumentId.CreateNewId(pid2);
var did3 = DocumentId.CreateNewId(pid3);
var text1 = @"
Public Class A
End Class";
var text2 = @"
Public Class B
End Class
";
var text3 = @"
public class C : B {
}
";
var text4 = @"
public class C : A {
}
";
var solution = new AdhocWorkspace().CurrentSolution
.AddProject(pid1, "GooA", "Goo.dll", LanguageNames.VisualBasic)
.AddDocument(did1, "A.vb", text1)
.AddMetadataReference(pid1, s_mscorlib)
.AddProject(pid2, "GooB", "Goo2.dll", LanguageNames.VisualBasic)
.AddDocument(did2, "B.vb", text2)
.AddMetadataReference(pid2, s_mscorlib)
.AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp)
.AddDocument(did3, "C.cs", text3)
.AddMetadataReference(pid3, s_mscorlib)
.AddProjectReference(pid3, new ProjectReference(pid1))
.AddProjectReference(pid3, new ProjectReference(pid2));
var project3 = solution.GetProject(pid3);
var comp3 = project3.GetCompilationAsync().Result;
var classC = comp3.GetTypeByMetadataName("C");
var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly);
Assert.Equal(pid2, projectForBaseType.Id);
// switch base type to A then try again
var solution2 = solution.WithDocumentText(did3, SourceText.From(text4));
project3 = solution2.GetProject(pid3);
comp3 = project3.GetCompilationAsync().Result;
classC = comp3.GetTypeByMetadataName("C");
projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly);
Assert.Equal(pid1, projectForBaseType.Id);
}
[WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")]
[Fact]
public void TestEncodingRetainedAfterTreeChanged()
{
var ws = new AdhocWorkspace();
var proj = ws.AddProject("proj", LanguageNames.CSharp);
var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32));
Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding);
// updating root doesn't change original encoding
var root = doc.GetSyntaxRootAsync().Result;
var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace(" ")));
var newDoc = doc.WithSyntaxRoot(newRoot);
Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding);
}
[Fact]
public void TestProjectWithNoBrokenReferencesHasNoIncompleteReferences()
{
var workspace = new AdhocWorkspace();
var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
var project2 = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(project1.Id) }));
// Nothing should have incomplete references, and everything should build
Assert.True(project1.HasSuccessfullyLoadedAsync().Result);
Assert.True(project2.HasSuccessfullyLoadedAsync().Result);
Assert.Single(project2.GetCompilationAsync().Result.ExternalReferences);
}
[Fact]
public void TestProjectWithBrokenCrossLanguageReferenceHasIncompleteReferences()
{
var workspace = new AdhocWorkspace();
var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class "));
var project2 = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(project1.Id) }));
Assert.True(project1.HasSuccessfullyLoadedAsync().Result);
Assert.False(project2.HasSuccessfullyLoadedAsync().Result);
Assert.Empty(project2.GetCompilationAsync().Result.ExternalReferences);
}
[Fact]
public async Task TestFrozenPartialProjectHasDifferentSemanticVersions()
{
using var workspace = CreateWorkspaceWithPartalSemantics();
var project = workspace.CurrentSolution.AddProject("CSharpProject", "CSharpProject", LanguageNames.CSharp);
project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
var documentToFreeze = project.AddDocument("DocumentToFreeze.cs", SourceText.From(""));
var frozenDocument = documentToFreeze.WithFrozenPartialSemantics(CancellationToken.None);
// Because we had no compilation produced yet, we expect that only the DocumentToFreeze is in the compilation
Assert.NotSame(frozenDocument, documentToFreeze);
var tree = Assert.Single((await frozenDocument.Project.GetCompilationAsync()).SyntaxTrees);
Assert.Equal("DocumentToFreeze.cs", tree.FilePath);
// Versions should be different
Assert.NotEqual(
await documentToFreeze.Project.GetDependentSemanticVersionAsync(),
await frozenDocument.Project.GetDependentSemanticVersionAsync());
Assert.NotEqual(
await documentToFreeze.Project.GetSemanticVersionAsync(),
await frozenDocument.Project.GetSemanticVersionAsync());
}
[Fact]
public void TestFrozenPartialProjectAlwaysIsIncomplete()
{
var workspace = new AdhocWorkspace();
var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
var project2 = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(project1.Id) }));
var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From(""));
// Nothing should have incomplete references, and everything should build
var frozenSolution = document.WithFrozenPartialSemantics(CancellationToken.None).Project.Solution;
Assert.True(frozenSolution.GetProject(project1.Id).HasSuccessfullyLoadedAsync().Result);
Assert.True(frozenSolution.GetProject(project2.Id).HasSuccessfullyLoadedAsync().Result);
}
[Fact]
public void TestProjectCompletenessWithMultipleProjects()
{
GetMultipleProjects(out var csBrokenProject, out var vbNormalProject, out var dependsOnBrokenProject, out var dependsOnVbNormalProject, out var transitivelyDependsOnBrokenProjects, out var transitivelyDependsOnNormalProjects);
// check flag for a broken project itself
Assert.False(csBrokenProject.HasSuccessfullyLoadedAsync().Result);
// check flag for a normal project itself
Assert.True(vbNormalProject.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that directly reference a broken project
Assert.True(dependsOnBrokenProject.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that directly reference only normal project
Assert.True(dependsOnVbNormalProject.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that indirectly reference a borken project
// normal project -> normal project -> broken project
Assert.True(transitivelyDependsOnBrokenProjects.HasSuccessfullyLoadedAsync().Result);
// check flag for normal project that indirectly reference only normal project
// normal project -> normal project -> normal project
Assert.True(transitivelyDependsOnNormalProjects.HasSuccessfullyLoadedAsync().Result);
}
[Fact]
public async Task TestMassiveFileSize()
{
// set max file length to 1 bytes
var maxLength = 1;
var workspace = new AdhocWorkspace();
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FileTextLoaderOptions.FileLengthThreshold, maxLength)));
using var root = new TempRoot();
var file = root.CreateFile(prefix: "massiveFile", extension: ".cs").WriteAllText("hello");
var loader = new FileTextLoader(file.Path, Encoding.UTF8);
var textLength = FileUtilities.GetFileLength(file.Path);
var expected = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, file.Path, textLength, maxLength);
var exceptionThrown = false;
try
{
// test async one
var unused = await loader.LoadTextAndVersionAsync(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None);
}
catch (InvalidDataException ex)
{
exceptionThrown = true;
Assert.Equal(expected, ex.Message);
}
Assert.True(exceptionThrown);
exceptionThrown = false;
try
{
// test sync one
var unused = loader.LoadTextAndVersionSynchronously(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None);
}
catch (InvalidDataException ex)
{
exceptionThrown = true;
Assert.Equal(expected, ex.Message);
}
Assert.True(exceptionThrown);
}
[Fact]
[WorkItem(18697, "https://github.com/dotnet/roslyn/issues/18697")]
public void TestWithSyntaxTree()
{
// get one to get to syntax tree factory
using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations();
var solution = workspace.CurrentSolution;
var dummyProject = solution.AddProject("dummy", "dummy", LanguageNames.CSharp);
var factory = dummyProject.LanguageServices.SyntaxTreeFactory;
// create the origin tree
var strongTree = factory.ParseSyntaxTree("dummy", dummyProject.ParseOptions, SourceText.From("// emtpy"), CancellationToken.None);
// create recoverable tree off the original tree
var recoverableTree = factory.CreateRecoverableTree(
dummyProject.Id,
strongTree.FilePath,
strongTree.Options,
new ConstantValueSource<TextAndVersion>(TextAndVersion.Create(strongTree.GetText(), VersionStamp.Create(), strongTree.FilePath)),
strongTree.GetText().Encoding,
strongTree.GetRoot());
// create new tree before it ever getting root node
var newTree = recoverableTree.WithFilePath("different/dummy");
// this shouldn't throw
_ = newTree.GetRoot();
}
[Fact]
public void TestUpdateDocumentsOrder()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
VersionStamp GetVersion() => solution.GetProject(pid).Version;
ImmutableArray<DocumentId> GetDocumentIds() => solution.GetProject(pid).DocumentIds.ToImmutableArray();
ImmutableArray<SyntaxTree> GetSyntaxTrees()
{
return solution.GetProject(pid).GetCompilationAsync().Result.SyntaxTrees.ToImmutableArray();
}
solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp);
var text1 = "public class Test1 {}";
var did1 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did1, "test1.cs", text1);
var text2 = "public class Test2 {}";
var did2 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did2, "test2.cs", text2);
var text3 = "public class Test3 {}";
var did3 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did3, "test3.cs", text3);
var text4 = "public class Test4 {}";
var did4 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did4, "test4.cs", text4);
var text5 = "public class Test5 {}";
var did5 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did5, "test5.cs", text5);
var oldVersion = GetVersion();
solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 }));
var newVersion = GetVersion();
// Make sure we have a new version because the order changed.
Assert.NotEqual(oldVersion, newVersion);
var documentIds = GetDocumentIds();
Assert.Equal(did5, documentIds[0]);
Assert.Equal(did4, documentIds[1]);
Assert.Equal(did3, documentIds[2]);
Assert.Equal(did2, documentIds[3]);
Assert.Equal(did1, documentIds[4]);
var syntaxTrees = GetSyntaxTrees();
Assert.Equal(documentIds.Count(), syntaxTrees.Count());
Assert.Equal("test5.cs", syntaxTrees[0].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test4.cs", syntaxTrees[1].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test3.cs", syntaxTrees[2].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test2.cs", syntaxTrees[3].FilePath, StringComparer.OrdinalIgnoreCase);
Assert.Equal("test1.cs", syntaxTrees[4].FilePath, StringComparer.OrdinalIgnoreCase);
solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 }));
var newSameVersion = GetVersion();
// Make sure we have the same new version because the order hasn't changed.
Assert.Equal(newVersion, newSameVersion);
}
[Fact]
public void TestUpdateDocumentsOrderExceptions()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var pid = ProjectId.CreateNewId();
solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp);
var text1 = "public class Test1 {}";
var did1 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did1, "test1.cs", text1);
var text2 = "public class Test2 {}";
var did2 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did2, "test2.cs", text2);
var text3 = "public class Test3 {}";
var did3 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did3, "test3.cs", text3);
var text4 = "public class Test4 {}";
var did4 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did4, "test4.cs", text4);
var text5 = "public class Test5 {}";
var did5 = DocumentId.CreateNewId(pid);
solution = solution.AddDocument(did5, "test5.cs", text5);
solution = solution.RemoveDocument(did5);
Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.Create<DocumentId>()));
Assert.Throws<ArgumentNullException>(() => solution = solution.WithProjectDocumentsOrder(pid, null));
Assert.Throws<InvalidOperationException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did3, did2, did1 })));
Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did3, did2, did1 })));
}
[Theory]
[CombinatorialData]
public async Task TestAddingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName)
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb";
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", languageName);
solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension);
var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync();
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var project = solution.GetProject(projectId);
var newCompilation = await project.GetCompilationAsync();
Assert.Same(originalSyntaxTree, newSyntaxTree);
Assert.NotSame(originalCompilation, newCompilation);
Assert.NotEqual(originalCompilation.Options, newCompilation.Options);
var provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.True(provider.TryGetDiagnosticValue(newSyntaxTree, "CA1234", CancellationToken.None, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
}
[Theory]
[CombinatorialData]
public async Task TestAddingAndRemovingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName)
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb";
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", languageName);
solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension);
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var syntaxTreeAfterAddingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var project = solution.GetProject(projectId);
var provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.True(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId);
project = solution.GetProject(projectId);
var syntaxTreeAfterRemovingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.False(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out _));
var finalCompilation = await project.GetCompilationAsync();
Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterRemovingEditorConfig));
}
[Theory]
[CombinatorialData]
public async Task TestChangingAnEditorConfigFile([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName, bool useRecoverableTrees)
{
using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace();
var solution = workspace.CurrentSolution;
var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb";
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", languageName);
solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension);
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var syntaxTreeBeforeEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var project = solution.GetProject(projectId);
var provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider);
Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA1234", CancellationToken.None, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
solution = solution.WithAnalyzerConfigDocumentTextLoader(
editorConfigDocumentId,
TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA6789.severity = error"), VersionStamp.Default)),
PreservationMode.PreserveValue);
var syntaxTreeAfterEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
project = solution.GetProject(projectId);
provider = project.CompilationOptions.SyntaxTreeOptionsProvider;
Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider);
Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA6789", CancellationToken.None, out severity));
Assert.Equal(ReportDiagnostic.Error, severity);
var finalCompilation = await project.GetCompilationAsync();
Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterEditorConfigChange));
}
[Fact]
public void TestAddingAndRemovingGlobalEditorConfigFileWithDiagnosticSeverity()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp);
solution = solution.AddDocument(sourceDocumentId, "Test.cs", "", filePath: @"Z:\Test.cs");
var originalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider;
Assert.False(originalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _));
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".globalconfig",
filePath: @"Z:\.globalconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("is_global = true\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
var newProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider;
Assert.True(newProvider.TryGetGlobalDiagnosticValue("CA1234", default, out var severity));
Assert.Equal(ReportDiagnostic.Error, severity);
solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId);
var finalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider;
Assert.False(finalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _));
}
[Fact]
[WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")]
public async Task TestAddingEditorConfigFileWithIsGeneratedCodeOption()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var sourceDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp)
.WithProjectMetadataReferences(projectId, new[] { TestMetadata.Net451.mscorlib })
.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable));
var src = @"
class C
{
void M(C? c)
{
_ = c.ToString(); // warning CS8602: Dereference of a possibly null reference.
}
}";
solution = solution.AddDocument(sourceDocumentId, "Test.cs", src, filePath: @"Z:\Test.cs");
var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync();
// warning CS8602: Dereference of a possibly null reference.
var diagnostics = originalCompilation.GetDiagnostics();
var diagnostic = Assert.Single(diagnostics);
Assert.Equal("CS8602", diagnostic.Id);
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create(
DocumentInfo.Create(
editorConfigDocumentId,
".editorconfig",
filePath: @"Z:\.editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ngenerated_code = true"), VersionStamp.Default)))));
var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync();
var newCompilation = await solution.GetProject(projectId).GetCompilationAsync();
Assert.Same(originalSyntaxTree, newSyntaxTree);
Assert.NotSame(originalCompilation, newCompilation);
Assert.NotEqual(originalCompilation.Options, newCompilation.Options);
// warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// Auto-generated code requires an explicit '#nullable' directive in source.
diagnostics = newCompilation.GetDiagnostics();
diagnostic = Assert.Single(diagnostics);
Assert.Contains("CS8669", diagnostic.Id);
}
[Fact]
public void NoCompilationProjectsHaveNullSyntaxTreesAndSemanticModels()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName);
solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt");
var document = solution.GetDocument(documentId)!;
Assert.False(document.TryGetSyntaxTree(out _));
Assert.Null(document.GetSyntaxTreeAsync().Result);
Assert.Null(document.GetSyntaxTreeSynchronously(CancellationToken.None));
Assert.False(document.TryGetSemanticModel(out _));
Assert.Null(document.GetSemanticModelAsync().Result);
}
[Fact]
public void ChangingFilePathOfFileInNoCompilationProjectWorks()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName);
solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt");
Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result);
solution = solution.WithDocumentFilePath(documentId, @"Z:\NewPath.txt");
Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result);
}
[Fact]
public void AddingAndRemovingProjectsUpdatesFilePathMap()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var projectId = ProjectId.CreateNewId();
var editorConfigDocumentId = DocumentId.CreateNewId(projectId);
const string editorConfigFilePath = @"Z:\.editorconfig";
var projectInfo =
ProjectInfo.Create(projectId, VersionStamp.Default, "Test", "Test", LanguageNames.CSharp)
.WithAnalyzerConfigDocuments(new[] { DocumentInfo.Create(editorConfigDocumentId, ".editorconfig", filePath: editorConfigFilePath) });
solution = solution.AddProject(projectInfo);
Assert.Equal(editorConfigDocumentId, Assert.Single(solution.GetDocumentIdsWithFilePath(editorConfigFilePath)));
solution = solution.RemoveProject(projectId);
Assert.Empty(solution.GetDocumentIdsWithFilePath(editorConfigFilePath));
}
private static void GetMultipleProjects(
out Project csBrokenProject,
out Project vbNormalProject,
out Project dependsOnBrokenProject,
out Project dependsOnVbNormalProject,
out Project transitivelyDependsOnBrokenProjects,
out Project transitivelyDependsOnNormalProjects)
{
var workspace = new AdhocWorkspace();
csBrokenProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"CSharpProject",
"CSharpProject",
LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false));
vbNormalProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic));
dependsOnBrokenProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(csBrokenProject.Id), new ProjectReference(vbNormalProject.Id) }));
dependsOnVbNormalProject = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"CSharpProject",
"CSharpProject",
LanguageNames.CSharp,
projectReferences: new[] { new ProjectReference(vbNormalProject.Id) }));
transitivelyDependsOnBrokenProjects = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"CSharpProject",
"CSharpProject",
LanguageNames.CSharp,
projectReferences: new[] { new ProjectReference(dependsOnBrokenProject.Id) }));
transitivelyDependsOnNormalProjects = workspace.AddProject(
ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
"VisualBasicProject",
"VisualBasicProject",
LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(dependsOnVbNormalProject.Id) }));
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestOptionChangesForLanguagesNotInSolution()
{
// Create an empty solution with no projects.
using var workspace = CreateWorkspace();
var s0 = workspace.CurrentSolution;
var optionService = workspace.Services.GetRequiredService<IOptionService>();
// Apply an option change to a C# option.
var option = GenerationOptions.PlaceSystemNamespaceFirst;
var defaultValue = option.DefaultValue;
var changedValue = !defaultValue;
var options = s0.Options.WithChangedOption(option, LanguageNames.CSharp, changedValue);
// Verify option change is preserved even if the solution has no project with that language.
var s1 = s0.WithOptions(options);
VerifyOptionSet(s1.Options);
// Verify option value is preserved on adding a project for a different language.
var s2 = s1.AddProject("P1", "A1", LanguageNames.VisualBasic).Solution;
VerifyOptionSet(s2.Options);
// Verify option value is preserved on roundtriping the option set (serialize and deserialize).
var s3 = s2.AddProject("P2", "A2", LanguageNames.CSharp).Solution;
var roundTripOptionSet = SerializeAndDeserialize((SerializableOptionSet)s3.Options, optionService);
VerifyOptionSet(roundTripOptionSet);
// Verify option value is preserved on removing a project.
var s4 = s3.RemoveProject(s3.Projects.Single(p => p.Name == "P2").Id);
VerifyOptionSet(s4.Options);
return;
void VerifyOptionSet(OptionSet optionSet)
{
Assert.Equal(changedValue, optionSet.GetOption(option, LanguageNames.CSharp));
Assert.Equal(defaultValue, optionSet.GetOption(option, LanguageNames.VisualBasic));
}
static SerializableOptionSet SerializeAndDeserialize(SerializableOptionSet optionSet, IOptionService optionService)
{
using var stream = new MemoryStream();
using var writer = new ObjectWriter(stream);
optionSet.Serialize(writer, CancellationToken.None);
stream.Position = 0;
using var reader = ObjectReader.TryGetReader(stream);
return SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None);
}
}
[Theory]
[CombinatorialData]
public async Task TestUpdatedDocumentTextIsObservablyConstantAsync(bool recoverable)
{
using var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace();
var pid = ProjectId.CreateNewId();
var text = SourceText.From("public class C { }");
var version = VersionStamp.Create();
var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
var projInfo = ProjectInfo.Create(
pid,
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp,
documents: new[] { docInfo });
var solution = workspace.CurrentSolution.AddProject(projInfo);
var doc = solution.GetDocument(docInfo.Id);
// change document
var root = await doc.GetSyntaxRootAsync();
var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());
Assert.NotSame(root, newRoot);
var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id);
Assert.NotSame(doc, newDoc);
var newDocText = await newDoc.GetTextAsync();
var sameText = await newDoc.GetTextAsync();
Assert.Same(newDocText, sameText);
var newDocTree = await newDoc.GetSyntaxTreeAsync();
var treeText = newDocTree.GetText();
Assert.Same(newDocText, treeText);
}
[Fact]
public async Task ReplacingTextMultipleTimesDoesNotRootIntermediateCopiesIfCompilationNotAskedFor()
{
// This test replicates the pattern of some operation changing a bunch of files, but the files aren't kept open.
// In Visual Studio we do large refactorings by opening files with an invisible editor, making changes, and closing
// again. This process means we'll queue up intermediate changes to those files, but we don't want to hold onto
// the intermediate edits when we don't really need to since the final version will be all that matters.
using var workspace = CreateWorkspaceWithProjectAndDocuments();
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.Single().DocumentIds.Single();
// Fetch the compilation, so further edits are going to be incremental updates of this one
var originalCompilation = await solution.Projects.Single().GetCompilationAsync();
// Create a source text we'll release and ensure it disappears. We'll also make sure we don't accidentally root
// that solution in the middle.
var sourceTextToRelease = ObjectReference.CreateFromFactory(static () => SourceText.From(Guid.NewGuid().ToString()));
var solutionWithSourceTextToRelease = sourceTextToRelease.GetObjectReference(
static (sourceText, document) => document.Project.Solution.WithDocumentText(document.Id, sourceText, PreservationMode.PreserveIdentity),
solution.GetDocument(documentId));
// Change it again, this time by editing the text loader; this replicates us closing a file, and we don't want to pin the changes from the
// prior change.
var finalSolution = solutionWithSourceTextToRelease.GetObjectReference(
static (s, documentId) => s.WithDocumentTextLoader(documentId, new TestTextLoader(Guid.NewGuid().ToString()), PreservationMode.PreserveValue), documentId).GetReference();
// The text in the middle shouldn't be held at all, since we replaced it.
solutionWithSourceTextToRelease.ReleaseStrongReference();
sourceTextToRelease.AssertReleased();
GC.KeepAlive(finalSolution);
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/Core/Portable/Syntax/SyntaxNavigator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class SyntaxNavigator
{
private const int None = 0;
public static readonly SyntaxNavigator Instance = new SyntaxNavigator();
private SyntaxNavigator()
{
}
[Flags]
private enum SyntaxKinds
{
DocComments = 1,
Directives = 2,
SkippedTokens = 4,
}
private static readonly Func<SyntaxTrivia, bool>?[] s_stepIntoFunctions = new Func<SyntaxTrivia, bool>?[]
{
/* 000 */ null,
/* 001 */ t => t.IsDocumentationCommentTrivia,
/* 010 */ t => t.IsDirective,
/* 011 */ t => t.IsDirective || t.IsDocumentationCommentTrivia,
/* 100 */ t => t.IsSkippedTokensTrivia,
/* 101 */ t => t.IsSkippedTokensTrivia || t.IsDocumentationCommentTrivia,
/* 110 */ t => t.IsSkippedTokensTrivia || t.IsDirective,
/* 111 */ t => t.IsSkippedTokensTrivia || t.IsDirective || t.IsDocumentationCommentTrivia,
};
private static Func<SyntaxTrivia, bool>? GetStepIntoFunction(
bool skipped, bool directives, bool docComments)
{
var index = (skipped ? SyntaxKinds.SkippedTokens : 0) |
(directives ? SyntaxKinds.Directives : 0) |
(docComments ? SyntaxKinds.DocComments : 0);
return s_stepIntoFunctions[(int)index];
}
private static Func<SyntaxToken, bool> GetPredicateFunction(bool includeZeroWidth)
{
return includeZeroWidth ? SyntaxToken.Any : SyntaxToken.NonZeroWidth;
}
private static bool Matches(Func<SyntaxToken, bool>? predicate, SyntaxToken token)
{
return predicate == null || ReferenceEquals(predicate, SyntaxToken.Any) || predicate(token);
}
internal SyntaxToken GetFirstToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetFirstToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetLastToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetLastToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetPreviousToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetNextToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetNextToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetPreviousToken(current, predicate, stepInto != null, stepInto);
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetNextToken(current, predicate, stepInto != null, stepInto);
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Enumerator>> s_childEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Enumerator>>(() => new Stack<ChildSyntaxList.Enumerator>(), 10);
internal SyntaxToken GetFirstToken(SyntaxNode current, Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childEnumeratorStackPool.Free(stack);
}
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>> s_childReversedEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>>(() => new Stack<ChildSyntaxList.Reversed.Enumerator>(), 10);
internal SyntaxToken GetLastToken(SyntaxNode current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childReversedEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().Reverse().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().Reverse().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childReversedEnumeratorStackPool.Free(stack);
}
}
private SyntaxToken GetFirstToken(
SyntaxTriviaList triviaList,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in triviaList)
{
if (trivia.TryGetStructure(out var structure) && stepInto(trivia))
{
var token = GetFirstToken(structure, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in list.Reverse())
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
return default;
}
private bool TryGetLastTokenForStructuredTrivia(
SyntaxTrivia trivia,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
out SyntaxToken token)
{
token = default;
if (!trivia.TryGetStructure(out var structure) || stepInto == null || !stepInto(trivia))
{
return false;
}
token = GetLastToken(structure, predicate, stepInto);
return token.RawKind != None;
}
private SyntaxToken GetFirstToken(
SyntaxToken token,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var firstToken = GetFirstToken(token.LeadingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var firstToken = GetFirstToken(token.TrailingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxToken token,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var lastToken = GetLastToken(token.TrailingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var lastToken = GetLastToken(token.LeadingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxTrivia current,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnNext = false;
// look inside leading trivia for current & next
var token = GetNextToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnNext && (predicate == null || predicate == SyntaxToken.Any || predicate(current.Token)))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetNextToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetNextToken(current.Token, predicate, false, stepInto);
}
internal SyntaxToken GetPreviousToken(
SyntaxTrivia current,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnPrevious = false;
// look inside leading trivia for current & next
var token = GetPreviousToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnPrevious && Matches(predicate, current.Token))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetPreviousToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetPreviousToken(current.Token, predicate, false, stepInto);
}
private SyntaxToken GetNextToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnNext)
{
foreach (var trivia in list)
{
if (returnNext)
{
if (trivia.TryGetStructure(out var structure) && stepInto != null && stepInto(trivia))
{
var token = GetFirstToken(structure!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (trivia == current)
{
returnNext = true;
}
}
return default;
}
private SyntaxToken GetPreviousToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnPrevious)
{
foreach (var trivia in list.Reverse())
{
if (returnPrevious)
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
else if (trivia == current)
{
returnPrevious = true;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxNode node,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// next token
bool returnNext = false;
foreach (var child in node.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnNext = true;
}
}
// didn't find the next token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetNextToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(
SyntaxNode node,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// previous token
bool returnPrevious = false;
foreach (var child in node.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnPrevious = true;
}
}
// didn't find the previous token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetPreviousToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool>? predicate, bool searchInsideCurrentTokenTrailingTrivia, Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenTrailingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenTrailingTrivia)
{
var firstToken = GetFirstToken(current.TrailingTrivia, predicate, stepInto!);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnNext = false;
foreach (var child in current.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnNext = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetNextToken(current.Parent, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, bool searchInsideCurrentTokenLeadingTrivia,
Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenLeadingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenLeadingTrivia)
{
var lastToken = GetLastToken(current.LeadingTrivia, predicate, stepInto!);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnPrevious = false;
foreach (var child in current.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnPrevious = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetPreviousToken(current.Parent, predicate, stepInto);
}
return 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class SyntaxNavigator
{
private const int None = 0;
public static readonly SyntaxNavigator Instance = new SyntaxNavigator();
private SyntaxNavigator()
{
}
[Flags]
private enum SyntaxKinds
{
DocComments = 1,
Directives = 2,
SkippedTokens = 4,
}
private static readonly Func<SyntaxTrivia, bool>?[] s_stepIntoFunctions = new Func<SyntaxTrivia, bool>?[]
{
/* 000 */ null,
/* 001 */ t => t.IsDocumentationCommentTrivia,
/* 010 */ t => t.IsDirective,
/* 011 */ t => t.IsDirective || t.IsDocumentationCommentTrivia,
/* 100 */ t => t.IsSkippedTokensTrivia,
/* 101 */ t => t.IsSkippedTokensTrivia || t.IsDocumentationCommentTrivia,
/* 110 */ t => t.IsSkippedTokensTrivia || t.IsDirective,
/* 111 */ t => t.IsSkippedTokensTrivia || t.IsDirective || t.IsDocumentationCommentTrivia,
};
private static Func<SyntaxTrivia, bool>? GetStepIntoFunction(
bool skipped, bool directives, bool docComments)
{
var index = (skipped ? SyntaxKinds.SkippedTokens : 0) |
(directives ? SyntaxKinds.Directives : 0) |
(docComments ? SyntaxKinds.DocComments : 0);
return s_stepIntoFunctions[(int)index];
}
private static Func<SyntaxToken, bool> GetPredicateFunction(bool includeZeroWidth)
{
return includeZeroWidth ? SyntaxToken.Any : SyntaxToken.NonZeroWidth;
}
private static bool Matches(Func<SyntaxToken, bool>? predicate, SyntaxToken token)
{
return predicate == null || ReferenceEquals(predicate, SyntaxToken.Any) || predicate(token);
}
internal SyntaxToken GetFirstToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetFirstToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetLastToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetLastToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetPreviousToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetNextToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetNextToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetPreviousToken(current, predicate, stepInto != null, stepInto);
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetNextToken(current, predicate, stepInto != null, stepInto);
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Enumerator>> s_childEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Enumerator>>(() => new Stack<ChildSyntaxList.Enumerator>(), 10);
internal SyntaxToken GetFirstToken(SyntaxNode current, Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childEnumeratorStackPool.Free(stack);
}
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>> s_childReversedEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>>(() => new Stack<ChildSyntaxList.Reversed.Enumerator>(), 10);
internal SyntaxToken GetLastToken(SyntaxNode current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childReversedEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().Reverse().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().Reverse().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childReversedEnumeratorStackPool.Free(stack);
}
}
private SyntaxToken GetFirstToken(
SyntaxTriviaList triviaList,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in triviaList)
{
if (trivia.TryGetStructure(out var structure) && stepInto(trivia))
{
var token = GetFirstToken(structure, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in list.Reverse())
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
return default;
}
private bool TryGetLastTokenForStructuredTrivia(
SyntaxTrivia trivia,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
out SyntaxToken token)
{
token = default;
if (!trivia.TryGetStructure(out var structure) || stepInto == null || !stepInto(trivia))
{
return false;
}
token = GetLastToken(structure, predicate, stepInto);
return token.RawKind != None;
}
private SyntaxToken GetFirstToken(
SyntaxToken token,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var firstToken = GetFirstToken(token.LeadingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var firstToken = GetFirstToken(token.TrailingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxToken token,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var lastToken = GetLastToken(token.TrailingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var lastToken = GetLastToken(token.LeadingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxTrivia current,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnNext = false;
// look inside leading trivia for current & next
var token = GetNextToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnNext && (predicate == null || predicate == SyntaxToken.Any || predicate(current.Token)))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetNextToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetNextToken(current.Token, predicate, false, stepInto);
}
internal SyntaxToken GetPreviousToken(
SyntaxTrivia current,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnPrevious = false;
// look inside leading trivia for current & next
var token = GetPreviousToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnPrevious && Matches(predicate, current.Token))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetPreviousToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetPreviousToken(current.Token, predicate, false, stepInto);
}
private SyntaxToken GetNextToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnNext)
{
foreach (var trivia in list)
{
if (returnNext)
{
if (trivia.TryGetStructure(out var structure) && stepInto != null && stepInto(trivia))
{
var token = GetFirstToken(structure!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (trivia == current)
{
returnNext = true;
}
}
return default;
}
private SyntaxToken GetPreviousToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnPrevious)
{
foreach (var trivia in list.Reverse())
{
if (returnPrevious)
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
else if (trivia == current)
{
returnPrevious = true;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxNode node,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// next token
bool returnNext = false;
foreach (var child in node.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnNext = true;
}
}
// didn't find the next token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetNextToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(
SyntaxNode node,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// previous token
bool returnPrevious = false;
foreach (var child in node.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnPrevious = true;
}
}
// didn't find the previous token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetPreviousToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool>? predicate, bool searchInsideCurrentTokenTrailingTrivia, Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenTrailingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenTrailingTrivia)
{
var firstToken = GetFirstToken(current.TrailingTrivia, predicate, stepInto!);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnNext = false;
foreach (var child in current.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnNext = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetNextToken(current.Parent, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, bool searchInsideCurrentTokenLeadingTrivia,
Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenLeadingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenLeadingTrivia)
{
var lastToken = GetLastToken(current.LeadingTrivia, predicate, stepInto!);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnPrevious = false;
foreach (var child in current.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnPrevious = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetPreviousToken(current.Parent, predicate, stepInto);
}
return default;
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/Core/Portable/RuleSet/InvalidRuleSetException.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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
{
/// <summary>
/// Represents errors that occur while parsing RuleSet files.
/// </summary>
internal class InvalidRuleSetException : Exception
{
public InvalidRuleSetException() { }
public InvalidRuleSetException(string message) : base(message) { }
public InvalidRuleSetException(string message, Exception inner) : base(message, inner) { }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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
{
/// <summary>
/// Represents errors that occur while parsing RuleSet files.
/// </summary>
internal class InvalidRuleSetException : Exception
{
public InvalidRuleSetException() { }
public InvalidRuleSetException(string message) : base(message) { }
public InvalidRuleSetException(string message, Exception inner) : base(message, inner) { }
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable
{
private readonly IDisposable? _connection;
private readonly DebuggingSessionId _sessionId;
private readonly Workspace _workspace;
public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId)
{
_connection = connection;
_sessionId = sessionId;
_workspace = workspace;
}
public void Dispose()
{
_connection?.Dispose();
}
private IEditAndContinueWorkspaceService GetLocalService()
=> _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken)
{
ImmutableArray<DocumentId> documentsToReanalyze;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze);
}
else
{
var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>(
(service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken),
cancellationToken).ConfigureAwait(false);
documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty;
}
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze);
}
public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken)
{
ImmutableArray<DocumentId> documentsToReanalyze;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze);
}
else
{
var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>(
(service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty;
}
var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync(
compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false);
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze);
// clear emit/apply diagnostics reported previously:
diagnosticUpdateSource.ClearDiagnostics();
Dispose();
}
public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : true;
}
public async ValueTask<(
ManagedModuleUpdates updates,
ImmutableArray<DiagnosticData> diagnostics,
ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync(
Solution solution,
ActiveStatementSpanProvider activeStatementSpanProvider,
IDiagnosticAnalyzerService diagnosticService,
EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource,
CancellationToken cancellationToken)
{
ManagedModuleUpdates moduleUpdates;
ImmutableArray<DiagnosticData> diagnosticData;
ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);
moduleUpdates = results.ModuleUpdates;
diagnosticData = results.GetDiagnosticData(solution);
rudeEdits = results.RudeEdits;
}
else
{
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
if (result.HasValue)
{
moduleUpdates = result.Value.ModuleUpdates;
diagnosticData = result.Value.Diagnostics;
rudeEdits = result.Value.RudeEdits;
}
else
{
moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty);
diagnosticData = ImmutableArray<DiagnosticData>.Empty;
rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty;
}
}
// clear emit/apply diagnostics reported previously:
diagnosticUpdateSource.ClearDiagnostics();
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId));
// report emit/apply diagnostics:
diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData);
return (moduleUpdates, diagnosticData, rudeEdits);
}
public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken)
{
ImmutableArray<DocumentId> documentsToReanalyze;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze);
}
else
{
var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>(
(service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty;
}
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze);
}
public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().DiscardSolutionUpdate(_sessionId);
return;
}
await client.TryInvokeAsync<IRemoteEditAndContinueService>(
(service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : null;
}
public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>(
solution,
(service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : null;
}
public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>(
solution,
(service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty;
}
public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>(
document.Project.Solution,
(service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable
{
private readonly IDisposable? _connection;
private readonly DebuggingSessionId _sessionId;
private readonly Workspace _workspace;
public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId)
{
_connection = connection;
_sessionId = sessionId;
_workspace = workspace;
}
public void Dispose()
{
_connection?.Dispose();
}
private IEditAndContinueWorkspaceService GetLocalService()
=> _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken)
{
ImmutableArray<DocumentId> documentsToReanalyze;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze);
}
else
{
var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>(
(service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken),
cancellationToken).ConfigureAwait(false);
documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty;
}
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze);
}
public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken)
{
ImmutableArray<DocumentId> documentsToReanalyze;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze);
}
else
{
var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>(
(service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty;
}
var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync(
compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false);
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze);
// clear emit/apply diagnostics reported previously:
diagnosticUpdateSource.ClearDiagnostics();
Dispose();
}
public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : true;
}
public async ValueTask<(
ManagedModuleUpdates updates,
ImmutableArray<DiagnosticData> diagnostics,
ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync(
Solution solution,
ActiveStatementSpanProvider activeStatementSpanProvider,
IDiagnosticAnalyzerService diagnosticService,
EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource,
CancellationToken cancellationToken)
{
ManagedModuleUpdates moduleUpdates;
ImmutableArray<DiagnosticData> diagnosticData;
ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);
moduleUpdates = results.ModuleUpdates;
diagnosticData = results.GetDiagnosticData(solution);
rudeEdits = results.RudeEdits;
}
else
{
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
if (result.HasValue)
{
moduleUpdates = result.Value.ModuleUpdates;
diagnosticData = result.Value.Diagnostics;
rudeEdits = result.Value.RudeEdits;
}
else
{
moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty);
diagnosticData = ImmutableArray<DiagnosticData>.Empty;
rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty;
}
}
// clear emit/apply diagnostics reported previously:
diagnosticUpdateSource.ClearDiagnostics();
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId));
// report emit/apply diagnostics:
diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData);
return (moduleUpdates, diagnosticData, rudeEdits);
}
public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken)
{
ImmutableArray<DocumentId> documentsToReanalyze;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze);
}
else
{
var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>(
(service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty;
}
// clear all reported rude edits:
diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze);
}
public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().DiscardSolutionUpdate(_sessionId);
return;
}
await client.TryInvokeAsync<IRemoteEditAndContinueService>(
(service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : null;
}
public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>(
solution,
(service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : null;
}
public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>(
solution,
(service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty;
}
public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);
}
var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>(
document.Project.Solution,
(service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty;
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractToMethodConverter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions;
namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery
{
/// <summary>
/// Provides a conversion to query.Method() like query.ToList(), query.Count().
/// </summary>
internal abstract class AbstractToMethodConverter : AbstractConverter
{
// It is "item" for for "list.Add(item)"
// It can be anything for "counter++". It will be ingored in the case.
private readonly ExpressionSyntax _selectExpression;
// It is "list" for "list.Add(item)"
// It is "counter" for "counter++"
private readonly ExpressionSyntax _modifyingExpression;
// Trivia around "counter++;" or "list.Add(item);". Required to keep comments.
private readonly SyntaxTrivia[] _trivia;
public AbstractToMethodConverter(
ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo,
ExpressionSyntax selectExpression,
ExpressionSyntax modifyingExpression,
SyntaxTrivia[] trivia) : base(forEachInfo)
{
_selectExpression = selectExpression;
_modifyingExpression = modifyingExpression;
_trivia = trivia;
}
protected abstract string MethodName { get; }
protected abstract bool CanReplaceInitialization(ExpressionSyntax expressionSyntax, CancellationToken cancellationToken);
protected abstract StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression);
public override void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken)
{
var queryOrLinqInvocationExpression = CreateQueryExpressionOrLinqInvocation(
_selectExpression, Enumerable.Empty<SyntaxToken>(), Enumerable.Empty<SyntaxToken>(), convertToQuery);
var previous = ForEachInfo.ForEachStatement.GetPreviousStatement();
if (previous != null && !previous.ContainsDirectives)
{
switch (previous.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
var variables = ((LocalDeclarationStatementSyntax)previous).Declaration.Variables;
var lastDeclaration = variables.Last();
// Check if
// var ...., list = new List<T>(); or var ..., counter = 0;
// is just before the foreach.
// If so, join the declaration with the query.
if (_modifyingExpression is IdentifierNameSyntax identifierName &&
lastDeclaration.Identifier.ValueText.Equals(identifierName.Identifier.ValueText) &&
CanReplaceInitialization(lastDeclaration.Initializer.Value, cancellationToken))
{
Convert(lastDeclaration.Initializer.Value, variables.Count == 1 ? (SyntaxNode)previous : lastDeclaration);
return;
}
break;
case SyntaxKind.ExpressionStatement:
// Check if
// list = new List<T>(); or counter = 0;
// is just before the foreach.
// If so, join the assignment with the query.
if (((ExpressionStatementSyntax)previous).Expression is AssignmentExpressionSyntax assignmentExpression &&
SymbolEquivalenceComparer.Instance.Equals(
ForEachInfo.SemanticModel.GetSymbolInfo(assignmentExpression.Left, cancellationToken).Symbol,
ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol) &&
CanReplaceInitialization(assignmentExpression.Right, cancellationToken))
{
Convert(assignmentExpression.Right, previous);
return;
}
break;
}
}
// At least, we already can convert to
// list.AddRange(query) or counter += query.Count();
editor.ReplaceNode(
ForEachInfo.ForEachStatement,
CreateDefaultStatement(queryOrLinqInvocationExpression, _modifyingExpression).WithAdditionalAnnotations(Formatter.Annotation));
return;
void Convert(ExpressionSyntax replacingExpression, SyntaxNode nodeToRemoveIfFollowedByReturn)
{
SyntaxTrivia[] leadingTrivia;
// Check if expressionAssigning is followed by a return statement.
var expresisonSymbol = ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol;
if (expresisonSymbol is ILocalSymbol &&
ForEachInfo.ForEachStatement.GetNextStatement() is ReturnStatementSyntax returnStatement &&
!returnStatement.ContainsDirectives &&
SymbolEquivalenceComparer.Instance.Equals(
expresisonSymbol, ForEachInfo.SemanticModel.GetSymbolInfo(returnStatement.Expression, cancellationToken).Symbol))
{
// Input:
// var list = new List<T>(); or var counter = 0;
// foreach(...)
// {
// ...
// ...
// list.Add(item); or counter++;
// }
// return list; or return counter;
//
// Output:
// return queryGenerated.ToList(); or return queryGenerated.Count();
replacingExpression = returnStatement.Expression;
leadingTrivia = GetTriviaFromNode(nodeToRemoveIfFollowedByReturn)
.Concat(SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression)).ToArray();
editor.RemoveNode(nodeToRemoveIfFollowedByReturn);
}
else
{
leadingTrivia = SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression);
}
editor.ReplaceNode(
replacingExpression,
CreateInvocationExpression(queryOrLinqInvocationExpression)
.WithCommentsFrom(leadingTrivia, _trivia).KeepCommentsAndAddElasticMarkers());
editor.RemoveNode(ForEachInfo.ForEachStatement);
}
static SyntaxTrivia[] GetTriviaFromVariableDeclarator(VariableDeclaratorSyntax variableDeclarator)
=> SyntaxNodeOrTokenExtensions.GetTrivia(variableDeclarator.Identifier, variableDeclarator.Initializer.EqualsToken, variableDeclarator.Initializer.Value);
static SyntaxTrivia[] GetTriviaFromNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
var localDeclaration = (LocalDeclarationStatementSyntax)node;
if (localDeclaration.Declaration.Variables.Count != 1)
{
throw ExceptionUtilities.Unreachable;
}
return new IEnumerable<SyntaxTrivia>[] {
SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.Declaration.Type),
GetTriviaFromVariableDeclarator(localDeclaration.Declaration.Variables[0]),
SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.SemicolonToken)}.Flatten().ToArray();
case SyntaxKind.VariableDeclarator:
return GetTriviaFromVariableDeclarator((VariableDeclaratorSyntax)node);
case SyntaxKind.ExpressionStatement:
if (((ExpressionStatementSyntax)node).Expression is AssignmentExpressionSyntax assignmentExpression)
{
return SyntaxNodeOrTokenExtensions.GetTrivia(
assignmentExpression.Left, assignmentExpression.OperatorToken, assignmentExpression.Right);
}
break;
}
throw ExceptionUtilities.Unreachable;
}
}
// query => query.Method()
// like query.Count() or query.ToList()
protected InvocationExpressionSyntax CreateInvocationExpression(ExpressionSyntax queryOrLinqInvocationExpression)
=> SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ParenthesizedExpression(queryOrLinqInvocationExpression),
SyntaxFactory.IdentifierName(MethodName))).WithAdditionalAnnotations(Formatter.Annotation);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions;
namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery
{
/// <summary>
/// Provides a conversion to query.Method() like query.ToList(), query.Count().
/// </summary>
internal abstract class AbstractToMethodConverter : AbstractConverter
{
// It is "item" for for "list.Add(item)"
// It can be anything for "counter++". It will be ingored in the case.
private readonly ExpressionSyntax _selectExpression;
// It is "list" for "list.Add(item)"
// It is "counter" for "counter++"
private readonly ExpressionSyntax _modifyingExpression;
// Trivia around "counter++;" or "list.Add(item);". Required to keep comments.
private readonly SyntaxTrivia[] _trivia;
public AbstractToMethodConverter(
ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo,
ExpressionSyntax selectExpression,
ExpressionSyntax modifyingExpression,
SyntaxTrivia[] trivia) : base(forEachInfo)
{
_selectExpression = selectExpression;
_modifyingExpression = modifyingExpression;
_trivia = trivia;
}
protected abstract string MethodName { get; }
protected abstract bool CanReplaceInitialization(ExpressionSyntax expressionSyntax, CancellationToken cancellationToken);
protected abstract StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression);
public override void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken)
{
var queryOrLinqInvocationExpression = CreateQueryExpressionOrLinqInvocation(
_selectExpression, Enumerable.Empty<SyntaxToken>(), Enumerable.Empty<SyntaxToken>(), convertToQuery);
var previous = ForEachInfo.ForEachStatement.GetPreviousStatement();
if (previous != null && !previous.ContainsDirectives)
{
switch (previous.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
var variables = ((LocalDeclarationStatementSyntax)previous).Declaration.Variables;
var lastDeclaration = variables.Last();
// Check if
// var ...., list = new List<T>(); or var ..., counter = 0;
// is just before the foreach.
// If so, join the declaration with the query.
if (_modifyingExpression is IdentifierNameSyntax identifierName &&
lastDeclaration.Identifier.ValueText.Equals(identifierName.Identifier.ValueText) &&
CanReplaceInitialization(lastDeclaration.Initializer.Value, cancellationToken))
{
Convert(lastDeclaration.Initializer.Value, variables.Count == 1 ? (SyntaxNode)previous : lastDeclaration);
return;
}
break;
case SyntaxKind.ExpressionStatement:
// Check if
// list = new List<T>(); or counter = 0;
// is just before the foreach.
// If so, join the assignment with the query.
if (((ExpressionStatementSyntax)previous).Expression is AssignmentExpressionSyntax assignmentExpression &&
SymbolEquivalenceComparer.Instance.Equals(
ForEachInfo.SemanticModel.GetSymbolInfo(assignmentExpression.Left, cancellationToken).Symbol,
ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol) &&
CanReplaceInitialization(assignmentExpression.Right, cancellationToken))
{
Convert(assignmentExpression.Right, previous);
return;
}
break;
}
}
// At least, we already can convert to
// list.AddRange(query) or counter += query.Count();
editor.ReplaceNode(
ForEachInfo.ForEachStatement,
CreateDefaultStatement(queryOrLinqInvocationExpression, _modifyingExpression).WithAdditionalAnnotations(Formatter.Annotation));
return;
void Convert(ExpressionSyntax replacingExpression, SyntaxNode nodeToRemoveIfFollowedByReturn)
{
SyntaxTrivia[] leadingTrivia;
// Check if expressionAssigning is followed by a return statement.
var expresisonSymbol = ForEachInfo.SemanticModel.GetSymbolInfo(_modifyingExpression, cancellationToken).Symbol;
if (expresisonSymbol is ILocalSymbol &&
ForEachInfo.ForEachStatement.GetNextStatement() is ReturnStatementSyntax returnStatement &&
!returnStatement.ContainsDirectives &&
SymbolEquivalenceComparer.Instance.Equals(
expresisonSymbol, ForEachInfo.SemanticModel.GetSymbolInfo(returnStatement.Expression, cancellationToken).Symbol))
{
// Input:
// var list = new List<T>(); or var counter = 0;
// foreach(...)
// {
// ...
// ...
// list.Add(item); or counter++;
// }
// return list; or return counter;
//
// Output:
// return queryGenerated.ToList(); or return queryGenerated.Count();
replacingExpression = returnStatement.Expression;
leadingTrivia = GetTriviaFromNode(nodeToRemoveIfFollowedByReturn)
.Concat(SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression)).ToArray();
editor.RemoveNode(nodeToRemoveIfFollowedByReturn);
}
else
{
leadingTrivia = SyntaxNodeOrTokenExtensions.GetTrivia(replacingExpression);
}
editor.ReplaceNode(
replacingExpression,
CreateInvocationExpression(queryOrLinqInvocationExpression)
.WithCommentsFrom(leadingTrivia, _trivia).KeepCommentsAndAddElasticMarkers());
editor.RemoveNode(ForEachInfo.ForEachStatement);
}
static SyntaxTrivia[] GetTriviaFromVariableDeclarator(VariableDeclaratorSyntax variableDeclarator)
=> SyntaxNodeOrTokenExtensions.GetTrivia(variableDeclarator.Identifier, variableDeclarator.Initializer.EqualsToken, variableDeclarator.Initializer.Value);
static SyntaxTrivia[] GetTriviaFromNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
var localDeclaration = (LocalDeclarationStatementSyntax)node;
if (localDeclaration.Declaration.Variables.Count != 1)
{
throw ExceptionUtilities.Unreachable;
}
return new IEnumerable<SyntaxTrivia>[] {
SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.Declaration.Type),
GetTriviaFromVariableDeclarator(localDeclaration.Declaration.Variables[0]),
SyntaxNodeOrTokenExtensions.GetTrivia(localDeclaration.SemicolonToken)}.Flatten().ToArray();
case SyntaxKind.VariableDeclarator:
return GetTriviaFromVariableDeclarator((VariableDeclaratorSyntax)node);
case SyntaxKind.ExpressionStatement:
if (((ExpressionStatementSyntax)node).Expression is AssignmentExpressionSyntax assignmentExpression)
{
return SyntaxNodeOrTokenExtensions.GetTrivia(
assignmentExpression.Left, assignmentExpression.OperatorToken, assignmentExpression.Right);
}
break;
}
throw ExceptionUtilities.Unreachable;
}
}
// query => query.Method()
// like query.Count() or query.ToList()
protected InvocationExpressionSyntax CreateInvocationExpression(ExpressionSyntax queryOrLinqInvocationExpression)
=> SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ParenthesizedExpression(queryOrLinqInvocationExpression),
SyntaxFactory.IdentifierName(MethodName))).WithAdditionalAnnotations(Formatter.Annotation);
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MethodTests.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.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MethodTests
Inherits BasicTestBase
<Fact>
Public Sub Methods1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1()
End Sub
Protected MustOverride Function m2$()
Friend NotOverridable Overloads Function m3() As D
End Function
Protected Friend Overridable Shadows Sub m4()
End Sub
Protected Overrides Sub m5()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Shared Function m6()
End Function
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(8, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim ctor = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, ctor.ContainingSymbol)
Assert.Same(classC, ctor.ContainingType)
Assert.Equal(".ctor", ctor.Name)
Assert.Equal(MethodKind.Constructor, ctor.MethodKind)
Assert.Equal(Accessibility.Public, ctor.DeclaredAccessibility)
Assert.Equal(0, ctor.TypeParameters.Length)
Assert.Equal(0, ctor.TypeArguments.Length)
Assert.False(ctor.IsGenericMethod)
Assert.False(ctor.IsMustOverride)
Assert.False(ctor.IsNotOverridable)
Assert.False(ctor.IsOverridable)
Assert.False(ctor.IsOverrides)
Assert.False(ctor.IsShared)
Assert.False(ctor.IsOverloads)
Assert.True(ctor.IsSub)
Assert.Equal("System.Void", ctor.ReturnType.ToTestDisplayString())
Assert.Equal(0, ctor.Parameters.Length)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.False(m1.IsRuntimeImplemented()) ' test for default implementation
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.True(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsSub)
Assert.False(m2.IsOverloads)
Assert.Equal("System.String", m2.ReturnType.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(Accessibility.Friend, m3.DeclaredAccessibility)
Assert.False(m3.IsMustOverride)
Assert.True(m3.IsNotOverridable)
Assert.False(m3.IsOverridable)
Assert.False(m3.IsOverrides)
Assert.False(m3.IsShared)
Assert.True(m3.IsOverloads)
Assert.False(m3.IsSub)
Assert.Equal("C.D", m3.ReturnType.ToTestDisplayString())
Dim m4 = DirectCast(membersOfC(5), MethodSymbol)
Assert.Equal(Accessibility.ProtectedOrFriend, m4.DeclaredAccessibility)
Assert.False(m4.IsMustOverride)
Assert.False(m4.IsNotOverridable)
Assert.True(m4.IsOverridable)
Assert.False(m4.IsOverrides)
Assert.False(m4.IsShared)
Assert.False(m4.IsOverloads)
Assert.True(m4.IsSub)
Dim m5 = DirectCast(membersOfC(6), MethodSymbol)
Assert.Equal(Accessibility.Protected, m5.DeclaredAccessibility)
Assert.False(m5.IsMustOverride)
Assert.False(m5.IsNotOverridable)
Assert.False(m5.IsOverridable)
Assert.True(m5.IsOverrides)
Assert.False(m5.IsShared)
Assert.True(m5.IsOverloads)
Assert.True(m5.IsSub)
Dim m6 = DirectCast(membersOfC(7), MethodSymbol)
Assert.Equal(Accessibility.Friend, m6.DeclaredAccessibility)
Assert.False(m6.IsMustOverride)
Assert.False(m6.IsNotOverridable)
Assert.False(m6.IsOverridable)
Assert.False(m6.IsOverrides)
Assert.True(m6.IsShared)
Assert.False(m6.IsSub)
Assert.Equal("System.Object", m6.ReturnType.ToTestDisplayString())
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<expected>
BC31411: 'C' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Public Partial Class C
~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Friend NotOverridable Overloads Function m3() As D
~~
BC30508: 'm3' cannot expose type 'C.D' in namespace '<Default>' through class 'C'.
Friend NotOverridable Overloads Function m3() As D
~
BC30284: sub 'm5' cannot be declared 'Overrides' because it does not override a sub in a base class.
Protected Overrides Sub m5()
~~
</expected>)
End Sub
<Fact>
Public Sub Methods2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Module M
Sub m1()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim moduleM = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim m1 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m1.ContainingSymbol)
Assert.Same(moduleM, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared) ' methods in a module are implicitly Shared
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub Constructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Public Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Sub New(x as string, y as integer)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(2, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim m2 = DirectCast(membersOfC(1), MethodSymbol)
Assert.Same(classC, m2.ContainingSymbol)
Assert.Same(classC, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Friend, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(2, m2.Parameters.Length)
Assert.Equal("x", m2.Parameters(0).Name)
Assert.Equal("System.String", m2.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("y", m2.Parameters(1).Name)
Assert.Equal("System.Int32", m2.Parameters(1).Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub SharedConstructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Shared Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Module M
Sub New()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim moduleM = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".cctor", m1.Name)
Assert.Equal(MethodKind.SharedConstructor, m1.MethodKind)
Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m2 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m2.ContainingSymbol)
Assert.Same(moduleM, m2.ContainingType)
Assert.Equal(".cctor", m2.Name)
Assert.Equal(MethodKind.SharedConstructor, m2.MethodKind)
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.True(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub DefaultConstructors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Class C
End Class
Public MustInherit Class D
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Structure S
End Structure
Public Module M
End Module
Public Interface I
End Interface
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Assert.Equal("C", classC.Name)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim classD = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Dim membersOfD = classD.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfD.Length)
Dim m2 = DirectCast(membersOfD(0), MethodSymbol)
Assert.Same(classD, m2.ContainingSymbol)
Assert.Same(classD, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
Dim interfaceI = DirectCast(globalNSmembers(2), NamedTypeSymbol)
Assert.Equal("I", interfaceI.Name)
Assert.Equal(0, interfaceI.GetMembers().Length())
Dim moduleM = DirectCast(globalNSmembers(3), NamedTypeSymbol)
Assert.Equal("M", moduleM.Name)
Assert.Equal(0, moduleM.GetMembers().Length())
Dim structureS = DirectCast(globalNSmembers(4), NamedTypeSymbol)
Assert.Equal("S", structureS.Name)
Assert.Equal(1, structureS.GetMembers().Length()) ' Implicit parameterless constructor
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1(x as D, ByRef y As Integer)
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Sub m2(a(), z, byref q, ParamArray w())
End Sub
Sub m3(x)
End Sub
Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Equal("m1", m1.Name)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.Same(classD, m1p1.Type)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Int32", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Int32", m1p2.ToTestDisplayString())
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(4, m2.Parameters.Length)
Dim m2p1 = m2.Parameters(0)
Assert.Equal("a", m2p1.Name)
Assert.Same(m2, m2p1.ContainingSymbol)
Assert.False(m2p1.HasExplicitDefaultValue)
Assert.False(m2p1.IsOptional)
Assert.False(m2p1.IsParamArray)
Assert.False(m2p1.IsByRef)
Assert.Equal("System.Object()", m2p1.Type.ToTestDisplayString())
Dim m2p2 = m2.Parameters(1)
Assert.Equal("z", m2p2.Name)
Assert.Same(m2, m2p2.ContainingSymbol)
Assert.False(m2p2.HasExplicitDefaultValue)
Assert.False(m2p2.IsOptional)
Assert.False(m2p2.IsParamArray)
Assert.Equal("System.Object", m2p2.Type.ToTestDisplayString())
Dim m2p3 = m2.Parameters(2)
Assert.Equal("q", m2p3.Name)
Assert.Same(m2, m2p3.ContainingSymbol)
Assert.False(m2p3.HasExplicitDefaultValue)
Assert.False(m2p3.IsOptional)
Assert.False(m2p3.IsParamArray)
Assert.True(m2p3.IsByRef)
Assert.Equal("System.Object", m2p3.Type.ToTestDisplayString())
Assert.Equal("ByRef q As System.Object", m2p3.ToTestDisplayString())
Dim m2p4 = m2.Parameters(3)
Assert.Equal("w", m2p4.Name)
Assert.Same(m2, m2p4.ContainingSymbol)
Assert.False(m2p4.HasExplicitDefaultValue)
Assert.False(m2p4.IsOptional)
Assert.True(m2p4.IsParamArray)
Assert.Equal(TypeKind.Array, m2p4.Type.TypeKind)
Assert.Equal("System.Object", DirectCast(m2p4.Type, ArrayTypeSymbol).ElementType.ToTestDisplayString())
Assert.Equal("System.Object()", m2p4.Type.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(1, m3.Parameters.Length)
Dim m3p1 = m3.Parameters(0)
Assert.Equal("x", m3p1.Name)
Assert.Same(m3, m3p1.ContainingSymbol)
Assert.False(m3p1.HasExplicitDefaultValue)
Assert.False(m3p1.IsOptional)
Assert.False(m3p1.IsParamArray)
Assert.Equal("System.Object", m3p1.Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodByRefParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Structure S
Function M(Byref x as Object, ByRef y As Byte) As Long
Return 0
End Function
End Structure
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim typeS = DirectCast(globalNS.GetTypeMembers("S").Single(), NamedTypeSymbol)
Dim m1 = DirectCast(typeS.GetMembers("M").Single(), MethodSymbol)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.True(m1p1.IsByRef)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Byte", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Byte", m1p2.ToTestDisplayString())
Assert.Equal("ValueType", m1p2.Type.BaseType.Name)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodTypeParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Partial Class C
Function m1(Of T, U)(x1 As T) As IEnumerable(Of U)
End Function
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(3, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.True(m1.IsGenericMethod)
Assert.Equal(2, m1.TypeParameters.Length)
Dim tpT = m1.TypeParameters(0)
Assert.Equal("T", tpT.Name)
Assert.Same(m1, tpT.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpT.Variance)
Dim tpU = m1.TypeParameters(1)
Assert.Equal("U", tpU.Name)
Assert.Same(m1, tpU.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpU.Variance)
Dim paramX1 = m1.Parameters(0)
Assert.Same(tpT, paramX1.Type)
Assert.Equal("T", paramX1.Type.ToTestDisplayString())
Assert.Same(tpU, DirectCast(m1.ReturnType, NamedTypeSymbol).TypeArguments(0))
Assert.Equal("System.Collections.Generic.IEnumerable(Of U)", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub ConstructGenericMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Class C(Of W)
Function m1(Of T, U)(p1 As T, p2 as W) As KeyValuePair(Of W, U))
End Function
Sub m2()
End Sub
Public Class D(Of X)
Sub m3(Of T)(p1 As T)
End Sub
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim constructedC = classC.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_Int32)}).AsImmutableOrNull())
Dim m1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Dim m2 = DirectCast(constructedC.GetMembers("m2")(0), MethodSymbol)
Assert.True(m1.CanConstruct)
Assert.True(m1.OriginalDefinition.CanConstruct)
Assert.Same(m1, m1.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.NotEqual(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0))
Assert.Same(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0).OriginalDefinition)
Assert.Same(m1, m1.TypeParameters(0).ContainingSymbol)
Assert.Equal(2, m1.Arity)
Assert.Same(m1, m1.Construct(m1.TypeParameters(0), m1.TypeParameters(1)))
Dim m1_1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Assert.Equal(m1, m1_1)
Assert.NotSame(m1, m1_1) ' Checks below need equal, but not identical symbols to test target scenarios!
Assert.Same(m1, m1.Construct(m1_1.TypeParameters(0), m1_1.TypeParameters(1)))
Dim alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(1), m1_1.TypeParameters(0))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(1))
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(0))
alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(0), constructedC)
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(0))
Assert.Same(alphaConstructedM1.TypeArguments(1), constructedC)
alphaConstructedM1 = m1.Construct(constructedC, m1_1.TypeParameters(1))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), constructedC)
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(1))
Assert.False(m2.CanConstruct)
Assert.False(m2.OriginalDefinition.CanConstruct)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.Throws(Of InvalidOperationException)(Sub() m2.OriginalDefinition.Construct(classC))
Assert.Throws(Of InvalidOperationException)(Sub() m2.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.OriginalDefinition.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.Construct(classC))
Dim constructedC_d = constructedC.GetTypeMembers("D").Single()
Dim m3 = DirectCast(constructedC_d.GetMembers("m3").Single(), MethodSymbol)
Assert.Equal(1, m3.Arity)
Assert.False(m3.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() m3.Construct(classC))
Dim d = classC.GetTypeMembers("D").Single()
m3 = DirectCast(d.GetMembers("m3").Single(), MethodSymbol)
Dim alphaConstructedM3 = m3.Construct(m1.TypeParameters(0))
Assert.NotSame(m3, alphaConstructedM3)
Assert.Same(m3, alphaConstructedM3.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), alphaConstructedM3.TypeArguments(0))
Assert.Equal("T", m1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", m1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, U)", m1.ReturnType.ToTestDisplayString())
Assert.Equal("T", m1.TypeParameters(0).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.Equal("U", m1.TypeParameters(1).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(1), m1.TypeArguments(1))
Assert.Same(m1, m1.ConstructedFrom)
Dim constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.Equal("System.String", constructedM1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", constructedM1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ReturnType.ToTestDisplayString())
Assert.Equal("T", constructedM1.TypeParameters(0).ToTestDisplayString())
Assert.Equal("System.String", constructedM1.TypeArguments(0).ToTestDisplayString())
Assert.Equal("U", constructedM1.TypeParameters(1).ToTestDisplayString())
Assert.Equal("System.Boolean", constructedM1.TypeArguments(1).ToTestDisplayString())
Assert.Same(m1, constructedM1.ConstructedFrom)
Assert.Equal("Function C(Of System.Int32).m1(Of System.String, System.Boolean)(p1 As System.String, p2 As System.Int32) As System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ToTestDisplayString())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
' Try wrong arity.
Assert.Throws(Of ArgumentException)(Sub()
Dim constructedM1WrongArity = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String)}).AsImmutableOrNull())
End Sub)
' Try identity substitution.
Dim identityM1 = m1.Construct(m1.OriginalDefinition.TypeParameters.As(Of TypeSymbol)())
Assert.NotEqual(m1, identityM1)
Assert.Same(m1, identityM1.ConstructedFrom)
m1 = DirectCast(classC.GetMembers("m1").Single(), MethodSymbol)
identityM1 = m1.Construct(m1.TypeParameters.As(Of TypeSymbol)())
Assert.Same(m1, identityM1)
constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
Dim constructedM1_2 = m1.Construct(compilation.GetSpecialType(SpecialType.System_Byte), compilation.GetSpecialType(SpecialType.System_Boolean))
Dim constructedM1_3 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.NotEqual(constructedM1, constructedM1_2)
Assert.Equal(constructedM1, constructedM1_3)
Dim p1 = constructedM1.Parameters(0)
Assert.Equal(0, p1.Ordinal)
Assert.Same(constructedM1, p1.ContainingSymbol)
Assert.Equal(p1, p1)
Assert.Equal(p1, constructedM1_3.Parameters(0))
Assert.Equal(p1.GetHashCode(), constructedM1_3.Parameters(0).GetHashCode())
Assert.NotEqual(m1.Parameters(0), p1)
Assert.NotEqual(constructedM1_2.Parameters(0), p1)
Dim constructedM3 = m3.Construct(compilation.GetSpecialType(SpecialType.System_String))
Assert.NotEqual(constructedM3.Parameters(0), p1)
End Sub
<Fact>
Public Sub InterfaceImplements01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Namespace NS
Public Class Abc
End Class
Public Interface IGoo(Of T)
Sub I1Sub1(ByRef p As T)
End Interface
Public Interface I1
Sub I1Sub1(ByRef p As String)
Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2 As Object()) As Integer
End Interface
Public Interface I2
Inherits I1
Sub I2Sub1()
Function I2Func1(ByRef p1 As aBC) As AbC
End Interface
End Namespace
</file>
<file name="b.vb">
Imports System.Collections.Generic
Namespace NS.NS1
Class Impl
Implements I2, IGoo(Of String)
Public Sub Sub1(ByRef p As String) Implements I1.I1Sub1, IGoo(Of String).I1Sub1
End Sub
Public Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2() As Object) As Integer Implements I1.I1Func1
Return p1
End Function
Public Function I2Func1(ByRef p1 As ABc) As ABC Implements I2.I2Func1
Return Nothing
End Function
Public Sub I2Sub1() Implements I2.I2Sub1
End Sub
End Class
Structure StructImpl(Of T)
Implements IGoo(Of T)
Public Sub Sub1(ByRef p As T) Implements IGoo(Of T).I1Sub1
End Sub
End Structure
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").AsEnumerable().SingleOrDefault(), NamespaceSymbol)
Dim ns1 = DirectCast(ns.GetMembers("NS1").Single(), NamespaceSymbol)
Dim classImpl = DirectCast(ns1.GetTypeMembers("impl").Single(), NamedTypeSymbol)
'direct interfaces
Assert.Equal(2, classImpl.Interfaces.Length)
Dim itfc = DirectCast(classImpl.Interfaces(0), NamedTypeSymbol)
Assert.Equal(1, itfc.Interfaces.Length)
itfc = DirectCast(itfc.Interfaces(0), NamedTypeSymbol)
Assert.Equal("I1", itfc.Name)
Dim mem1 = DirectCast(classImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(2, mem1.ExplicitInterfaceImplementation.Count)
mem1 = DirectCast(classImpl.GetMembers("i2Func1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count)
Dim param = DirectCast(mem1.Parameters(0), ParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal("ByRef " & param.Name & " As NS.Abc", param.ToTestDisplayString()) ' use case of declare's name
Dim structImpl = DirectCast(ns1.GetTypeMembers("structimpl").Single(), NamedTypeSymbol)
Assert.Equal(1, structImpl.Interfaces.Length)
Dim mem2 = DirectCast(structImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<WorkItem(537444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537444")>
<Fact>
Public Sub DeclareFunction01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Explicit
Imports System
Imports System.Runtime.InteropServices
Public Structure S1
Public strVar As String
Public x As Integer
End Structure
Namespace NS
Friend Module MyMod
Declare Ansi Function VerifyString2 Lib "AttrUsgOthM010DLL.dll" (ByRef Arg As S1, ByVal Op As Integer) As String
End Module
Class cls1
Overloads Declare Sub Goo Lib "someLib" ()
Overloads Sub goo(ByRef arg As Integer)
' ...
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim nsNS = DirectCast(compilation.Assembly.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim modOfNS = DirectCast(nsNS.GetMembers("MyMod").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(modOfNS.GetMembers().First(), MethodSymbol)
Assert.Equal("VerifyString2", mem1.Name)
' TODO: add more verification when this is working
End Sub
<Fact>
Public Sub CodepageOptionUnicodeMembers01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Module Module2
Sub ÛÊÛÄÁÍäá() ' 1067
Console.WriteLine (CStr(AscW("ÛÊÛÄÁÍäá")))
End Sub
End Module
Class Class1
Public Shared Sub ŒŸõ()
Console.WriteLine(CStr(AscW("ŒŸõ"))) ' 26908
End Sub
Friend Function [Widening](ByVal Ÿü As Short) As à–¾ 'invalid char in Dev10
Return New à–¾(Ÿü)
End Function
End Class
Structure ĵÁiÛE
Const str1 As String = "ĵÁiÛE" ' 1044
Dim i As Integer
End Structure
Public Class [Narrowing] 'êàê èäåíòèôèêàòîð.
Public ñëîâî As [CULng]
End Class
Public Structure [CULng]
Public [UInteger] As Integer
End Structure
</file>
</compilation>)
Dim glbNS = compilation.Assembly.GlobalNamespace
Dim type1 = DirectCast(glbNS.GetMembers("Module2").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(type1.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem1.DeclaredAccessibility)
Assert.True(mem1.IsSub)
Assert.Equal("Sub Module2.ÛÊÛÄÁÍäá()", mem1.ToTestDisplayString())
Dim type2 = DirectCast(glbNS.GetMembers("Class1").Single(), NamedTypeSymbol)
Dim mem2 = DirectCast(type2.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem2.DeclaredAccessibility)
'Assert.Equal("ŒŸõ", mem2.Name) - TODO: Code Page issue
Dim type3 = DirectCast(glbNS.GetTypeMembers("ĵÁiÛE").Single(), NamedTypeSymbol)
Dim mem3 = DirectCast(type3.GetMembers("Str1").Single(), FieldSymbol)
Assert.True(mem3.IsConst)
Assert.Equal("ĵÁiÛE.str1 As System.String", mem3.ToTestDisplayString())
Dim type4 = DirectCast(glbNS.GetTypeMembers("Narrowing").Single(), NamedTypeSymbol)
Dim mem4 = DirectCast(type4.GetMembers("ñëîâî").Single(), FieldSymbol)
Assert.Equal(TypeKind.Structure, mem4.Type.TypeKind)
End Sub
<WorkItem(537466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537466")>
<Fact>
Public Sub DefaultAccessibility01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Interface GI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class GC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Class
Structure GS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Structure
Namespace NS
Interface NI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class NC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Class
Structure NS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Structure
End Namespace
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
' interface - public
Dim typemem = DirectCast(globalNS.GetTypeMembers("GI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
Dim mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Class - field (private), other - public
typemem = DirectCast(globalNS.GetTypeMembers("GC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Struct - public
typemem = DirectCast(globalNS.GetTypeMembers("GS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
Dim nsNS = DirectCast(globalNS.GetMembers("NS").Single(), NamespaceSymbol)
typemem = DirectCast(nsNS.GetTypeMembers("NI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
End Sub
<Fact>
Public Sub OverloadsAndOverrides01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim derive = New NS.C2()
derive.Goo(1) ' call derived Goo
derive.Bar(1) ' call derived Bar
derive.Boo(1) ' call derived Boo
derive.VGoo(1) ' call derived VGoo
derive.VBar(1) ' call derived VBar
derive.VBoo(1) ' call derived VBoo
Console.WriteLine("-------------")
Dim base As NS.C1 = New NS.C2()
base.Goo(1) ' call base Goo
base.Bar(1) ' call base Bar
base.Boo(1) ' call base Boo
base.VGoo(1) ' call base Goo
base.VBar(1) ' call D
base.VBoo(1) ' call D
End Sub
End Module
Namespace NS
Public Class C1
Public Sub Goo(ByVal p As Integer)
Console.WriteLine("Base - Goo")
End Sub
Public Sub Bar(ByVal p As Integer)
Console.WriteLine("Base - Bar")
End Sub
Public Sub Boo(ByVal p As Integer)
Console.WriteLine("Base - Boo")
End Sub
Public Overridable Sub VGoo(ByVal p As Integer)
Console.WriteLine("Base - VGoo")
End Sub
Public Overridable Sub VBar(ByVal p As Integer)
Console.WriteLine("Base - VBar")
End Sub
Public Overridable Sub VBoo(ByVal p As Integer)
Console.WriteLine("Base - VBoo")
End Sub
End Class
Public Class C2
Inherits C1
Public Shadows Sub Goo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows Goo")
End Sub
Public Overloads Sub Bar(Optional ByVal p As Integer = 1)
Console.WriteLine("Derived - Overloads Bar")
End Sub
' warning
Public Sub Boo(Optional ByVal p As Integer = 2)
Console.WriteLine("Derived - Boo")
End Sub
' not virtual
Public Shadows Sub VGoo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows VGoo")
End Sub
' hidebysig and virtual
Public Overloads Overrides Sub VBar(ByVal p As Integer)
Console.WriteLine("Derived - Overloads Overrides VBar")
End Sub
' virtual
Public Overrides Sub VBoo(ByVal p As Integer)
Console.WriteLine("Derived - Overrides VBoo")
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetTypeMembers("C1").Single(), NamedTypeSymbol)
Dim mem = DirectCast(type1.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverridable)
mem = DirectCast(type1.GetMembers("VGoo").Single(), MethodSymbol)
Assert.True(mem.IsOverridable)
Dim type2 = DirectCast(ns.GetTypeMembers("C2").Single(), NamedTypeSymbol)
mem = DirectCast(type2.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Bar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Boo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
' overridable
mem = DirectCast(type2.GetMembers("VGoo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
Assert.False(mem.IsOverrides)
Assert.False(mem.IsOverridable)
mem = DirectCast(type2.GetMembers("VBar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
mem = DirectCast(type2.GetMembers("VBoo").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
End Sub
<Fact>
Public Sub Bug2820()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Class Class1
sub Test(x as T)
End sub
End Class
</file>
</compilation>)
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim test = class1.GetMembers("Test").OfType(Of MethodSymbol)().Single()
Assert.Equal("T", test.Parameters(0).Type.Name)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Sub baNana()
End Sub
Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Sub baNANa(xyz as String)
End Sub
Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' No "Overloads", so all methods should match first overloads in first source file
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNana").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNana" (from first file supplied to compilation).
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
If m.Parameters.Any Then
Assert.NotEqual("baNana", m.Name)
End If
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub baNANa(xyz as String)
End Sub
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overloads" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Overridable Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overrides Sub baNANa(xyz as String, a as integer)
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overrides" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BANANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, so all methods should match methods in base
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BAnANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, but base methods have multiple casing, so don't use it.
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "baNana".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub ProbableExtensionMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C">
<file name="a.vb">
Option Strict On
Class C1
Sub X()
goodext1()
goodext2()
goodext3()
goodext4()
goodext5()
goodext6()
goodext7()
goodext8()
badext1()
badext2()
badext3()
badext4()
badext5()
badext6()
End Sub
End Class
Namespace Blah
Class ExtensionAttribute
Inherits System.Attribute
End Class
End Namespace
</file>
<file name="b.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Runtime.CompilerServices
Imports ExAttribute = System.Runtime.CompilerServices.ExtensionAttribute
Imports Ex2 = System.Runtime.CompilerServices.ExtensionAttribute
Module M1
<[Extension]>
Public Sub goodext1(this As C1)
End Sub
<ExtensionAttribute>
Public Sub goodext2(this As C1)
End Sub
<System.Runtime.CompilerServices.Extension>
Public Sub goodext3(this As C1)
End Sub
<System.Runtime.CompilerServices.ExtensionAttribute>
Public Sub goodext4(this As C1)
End Sub
<[ExAttribute]>
Public Sub goodext5(this As C1)
End Sub
<Ex>
Public Sub goodext6(this As C1)
End Sub
<Ex2>
Public Sub goodext7(this As C1)
End Sub
<AnExt>
Public Sub goodext8(this As C1)
End Sub
<AnExt>
Declare Sub goodext9 Lib "goo" (this As C1)
<Blah.Extension>
Public Sub badext1(this As C1)
End Sub
<Blah.ExtensionAttribute>
Public Sub badext2(this As C1)
End Sub
<Extension>
Public Sub badext3()
End Sub
End Module
]]></file>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System
Imports Blah
Module M2
<Extension>
Public Sub badext4(this As C1)
End Sub
<ExtensionAttribute>
Public Sub badext5(this As C1)
End Sub
<Extension>
Declare Sub badext6 Lib "goo" (this As C1)
End Module
]]></file>
</compilation>, references:={TestMetadata.Net40.SystemCore, TestMetadata.Net40.System}, options:=TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse("AnExt=System.Runtime.CompilerServices.ExtensionAttribute")))
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim modM1 = DirectCast(globalNS.GetMembers("M1").Single(), NamedTypeSymbol)
Dim modM2 = DirectCast(globalNS.GetMembers("M2").Single(), NamedTypeSymbol)
Dim goodext1 = DirectCast(modM1.GetMembers("goodext1").Single(), MethodSymbol)
Assert.True(goodext1.IsExtensionMethod)
Assert.True(goodext1.MayBeReducibleExtensionMethod)
Dim goodext2 = DirectCast(modM1.GetMembers("goodext2").Single(), MethodSymbol)
Assert.True(goodext2.IsExtensionMethod)
Assert.True(goodext2.MayBeReducibleExtensionMethod)
Dim goodext3 = DirectCast(modM1.GetMembers("goodext3").Single(), MethodSymbol)
Assert.True(goodext3.IsExtensionMethod)
Assert.True(goodext3.MayBeReducibleExtensionMethod)
Dim goodext4 = DirectCast(modM1.GetMembers("goodext4").Single(), MethodSymbol)
Assert.True(goodext4.IsExtensionMethod)
Assert.True(goodext4.MayBeReducibleExtensionMethod)
Dim goodext5 = DirectCast(modM1.GetMembers("goodext5").Single(), MethodSymbol)
Assert.True(goodext5.IsExtensionMethod)
Assert.True(goodext5.MayBeReducibleExtensionMethod)
Dim goodext6 = DirectCast(modM1.GetMembers("goodext6").Single(), MethodSymbol)
Assert.True(goodext6.IsExtensionMethod)
Assert.True(goodext6.MayBeReducibleExtensionMethod)
Dim goodext7 = DirectCast(modM1.GetMembers("goodext7").Single(), MethodSymbol)
Assert.True(goodext7.IsExtensionMethod)
Assert.True(goodext7.MayBeReducibleExtensionMethod)
Dim goodext8 = DirectCast(modM1.GetMembers("goodext8").Single(), MethodSymbol)
Assert.True(goodext8.IsExtensionMethod)
Assert.True(goodext8.MayBeReducibleExtensionMethod)
Dim goodext9 = DirectCast(modM1.GetMembers("goodext9").Single(), MethodSymbol)
Assert.True(goodext9.IsExtensionMethod)
Assert.True(goodext9.MayBeReducibleExtensionMethod)
Dim badext1 = DirectCast(modM1.GetMembers("badext1").Single(), MethodSymbol)
Assert.False(badext1.IsExtensionMethod)
Assert.True(badext1.MayBeReducibleExtensionMethod)
Dim badext2 = DirectCast(modM1.GetMembers("badext2").Single(), MethodSymbol)
Assert.False(badext2.IsExtensionMethod)
Assert.True(badext2.MayBeReducibleExtensionMethod)
Dim badext3 = DirectCast(modM1.GetMembers("badext3").Single(), MethodSymbol)
Assert.False(badext3.IsExtensionMethod)
Assert.True(badext3.MayBeReducibleExtensionMethod)
Dim badext4 = DirectCast(modM2.GetMembers("badext4").Single(), MethodSymbol)
Assert.False(badext4.IsExtensionMethod)
Assert.True(badext4.MayBeReducibleExtensionMethod)
Dim badext5 = DirectCast(modM2.GetMembers("badext5").Single(), MethodSymbol)
Assert.False(badext5.IsExtensionMethod)
Assert.True(badext5.MayBeReducibleExtensionMethod)
Dim badext6 = DirectCast(modM2.GetMembers("badext6").Single(), MethodSymbol)
Assert.False(badext6.IsExtensionMethod)
Assert.True(badext6.MayBeReducibleExtensionMethod)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext1(this As C1)'.
badext1()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext2(this As C1)'.
badext2()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext4(this As C1)'.
badext4()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext5(this As C1)'.
badext5()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Declare Ansi Sub badext6 Lib "goo" (this As C1)'.
badext6()
~~~~~~~
BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend.
Public Sub badext3()
~~~~~~~
</expected>)
End Sub
<WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")>
<Fact>
Public Sub UserDefinedOperatorLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(c As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim operatorPos = source.IndexOf("+"c)
Dim parenPos = source.IndexOf("("c)
Dim comp = CreateCompilationWithMscorlib40({Parse(source)})
Dim Symbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single()
Dim span = Symbol.Locations.Single().SourceSpan
Assert.Equal(operatorPos, span.Start)
Assert.Equal(parenPos, span.End)
End Sub
<WorkItem(901815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/901815")>
<Fact>
Public Sub UserDefinedConversionLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(Of T)
Return Nothing
End Operator
End Class
]]>.Value
' Used to raise an exception.
Dim comp = CreateCompilationWithMscorlib40({Parse(source)}, options:=TestOptions.ReleaseDll)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC33016: Operator '+' must have either one or two parameters.
Public Shared Operator +(Of T)
~
BC30198: ')' expected.
Public Shared Operator +(Of T)
~
BC30199: '(' expected.
Public Shared Operator +(Of T)
~
BC32065: Type parameters cannot be specified on this declaration.
Public Shared Operator +(Of T)
~~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnNonPartial()
Dim source = <![CDATA[
Public Class C
Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.False(m.IsPartialDefinition)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnPartialDefinitionOnly()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.Null(m.PartialImplementationPart)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionWithPartialImplementation()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
Private Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.False(m.PartialImplementationPart.IsPartialDefinition)
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.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MethodTests
Inherits BasicTestBase
<Fact>
Public Sub Methods1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1()
End Sub
Protected MustOverride Function m2$()
Friend NotOverridable Overloads Function m3() As D
End Function
Protected Friend Overridable Shadows Sub m4()
End Sub
Protected Overrides Sub m5()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Shared Function m6()
End Function
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(8, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim ctor = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, ctor.ContainingSymbol)
Assert.Same(classC, ctor.ContainingType)
Assert.Equal(".ctor", ctor.Name)
Assert.Equal(MethodKind.Constructor, ctor.MethodKind)
Assert.Equal(Accessibility.Public, ctor.DeclaredAccessibility)
Assert.Equal(0, ctor.TypeParameters.Length)
Assert.Equal(0, ctor.TypeArguments.Length)
Assert.False(ctor.IsGenericMethod)
Assert.False(ctor.IsMustOverride)
Assert.False(ctor.IsNotOverridable)
Assert.False(ctor.IsOverridable)
Assert.False(ctor.IsOverrides)
Assert.False(ctor.IsShared)
Assert.False(ctor.IsOverloads)
Assert.True(ctor.IsSub)
Assert.Equal("System.Void", ctor.ReturnType.ToTestDisplayString())
Assert.Equal(0, ctor.Parameters.Length)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.False(m1.IsRuntimeImplemented()) ' test for default implementation
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.True(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsSub)
Assert.False(m2.IsOverloads)
Assert.Equal("System.String", m2.ReturnType.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(Accessibility.Friend, m3.DeclaredAccessibility)
Assert.False(m3.IsMustOverride)
Assert.True(m3.IsNotOverridable)
Assert.False(m3.IsOverridable)
Assert.False(m3.IsOverrides)
Assert.False(m3.IsShared)
Assert.True(m3.IsOverloads)
Assert.False(m3.IsSub)
Assert.Equal("C.D", m3.ReturnType.ToTestDisplayString())
Dim m4 = DirectCast(membersOfC(5), MethodSymbol)
Assert.Equal(Accessibility.ProtectedOrFriend, m4.DeclaredAccessibility)
Assert.False(m4.IsMustOverride)
Assert.False(m4.IsNotOverridable)
Assert.True(m4.IsOverridable)
Assert.False(m4.IsOverrides)
Assert.False(m4.IsShared)
Assert.False(m4.IsOverloads)
Assert.True(m4.IsSub)
Dim m5 = DirectCast(membersOfC(6), MethodSymbol)
Assert.Equal(Accessibility.Protected, m5.DeclaredAccessibility)
Assert.False(m5.IsMustOverride)
Assert.False(m5.IsNotOverridable)
Assert.False(m5.IsOverridable)
Assert.True(m5.IsOverrides)
Assert.False(m5.IsShared)
Assert.True(m5.IsOverloads)
Assert.True(m5.IsSub)
Dim m6 = DirectCast(membersOfC(7), MethodSymbol)
Assert.Equal(Accessibility.Friend, m6.DeclaredAccessibility)
Assert.False(m6.IsMustOverride)
Assert.False(m6.IsNotOverridable)
Assert.False(m6.IsOverridable)
Assert.False(m6.IsOverrides)
Assert.True(m6.IsShared)
Assert.False(m6.IsSub)
Assert.Equal("System.Object", m6.ReturnType.ToTestDisplayString())
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<expected>
BC31411: 'C' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Public Partial Class C
~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Friend NotOverridable Overloads Function m3() As D
~~
BC30508: 'm3' cannot expose type 'C.D' in namespace '<Default>' through class 'C'.
Friend NotOverridable Overloads Function m3() As D
~
BC30284: sub 'm5' cannot be declared 'Overrides' because it does not override a sub in a base class.
Protected Overrides Sub m5()
~~
</expected>)
End Sub
<Fact>
Public Sub Methods2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Module M
Sub m1()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim moduleM = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim m1 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m1.ContainingSymbol)
Assert.Same(moduleM, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared) ' methods in a module are implicitly Shared
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub Constructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Public Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Sub New(x as string, y as integer)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(2, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim m2 = DirectCast(membersOfC(1), MethodSymbol)
Assert.Same(classC, m2.ContainingSymbol)
Assert.Same(classC, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Friend, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(2, m2.Parameters.Length)
Assert.Equal("x", m2.Parameters(0).Name)
Assert.Equal("System.String", m2.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("y", m2.Parameters(1).Name)
Assert.Equal("System.Int32", m2.Parameters(1).Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub SharedConstructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Shared Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Module M
Sub New()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim moduleM = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".cctor", m1.Name)
Assert.Equal(MethodKind.SharedConstructor, m1.MethodKind)
Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m2 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m2.ContainingSymbol)
Assert.Same(moduleM, m2.ContainingType)
Assert.Equal(".cctor", m2.Name)
Assert.Equal(MethodKind.SharedConstructor, m2.MethodKind)
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.True(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub DefaultConstructors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Class C
End Class
Public MustInherit Class D
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Structure S
End Structure
Public Module M
End Module
Public Interface I
End Interface
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Assert.Equal("C", classC.Name)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim classD = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Dim membersOfD = classD.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfD.Length)
Dim m2 = DirectCast(membersOfD(0), MethodSymbol)
Assert.Same(classD, m2.ContainingSymbol)
Assert.Same(classD, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
Dim interfaceI = DirectCast(globalNSmembers(2), NamedTypeSymbol)
Assert.Equal("I", interfaceI.Name)
Assert.Equal(0, interfaceI.GetMembers().Length())
Dim moduleM = DirectCast(globalNSmembers(3), NamedTypeSymbol)
Assert.Equal("M", moduleM.Name)
Assert.Equal(0, moduleM.GetMembers().Length())
Dim structureS = DirectCast(globalNSmembers(4), NamedTypeSymbol)
Assert.Equal("S", structureS.Name)
Assert.Equal(1, structureS.GetMembers().Length()) ' Implicit parameterless constructor
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1(x as D, ByRef y As Integer)
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Sub m2(a(), z, byref q, ParamArray w())
End Sub
Sub m3(x)
End Sub
Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Equal("m1", m1.Name)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.Same(classD, m1p1.Type)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Int32", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Int32", m1p2.ToTestDisplayString())
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(4, m2.Parameters.Length)
Dim m2p1 = m2.Parameters(0)
Assert.Equal("a", m2p1.Name)
Assert.Same(m2, m2p1.ContainingSymbol)
Assert.False(m2p1.HasExplicitDefaultValue)
Assert.False(m2p1.IsOptional)
Assert.False(m2p1.IsParamArray)
Assert.False(m2p1.IsByRef)
Assert.Equal("System.Object()", m2p1.Type.ToTestDisplayString())
Dim m2p2 = m2.Parameters(1)
Assert.Equal("z", m2p2.Name)
Assert.Same(m2, m2p2.ContainingSymbol)
Assert.False(m2p2.HasExplicitDefaultValue)
Assert.False(m2p2.IsOptional)
Assert.False(m2p2.IsParamArray)
Assert.Equal("System.Object", m2p2.Type.ToTestDisplayString())
Dim m2p3 = m2.Parameters(2)
Assert.Equal("q", m2p3.Name)
Assert.Same(m2, m2p3.ContainingSymbol)
Assert.False(m2p3.HasExplicitDefaultValue)
Assert.False(m2p3.IsOptional)
Assert.False(m2p3.IsParamArray)
Assert.True(m2p3.IsByRef)
Assert.Equal("System.Object", m2p3.Type.ToTestDisplayString())
Assert.Equal("ByRef q As System.Object", m2p3.ToTestDisplayString())
Dim m2p4 = m2.Parameters(3)
Assert.Equal("w", m2p4.Name)
Assert.Same(m2, m2p4.ContainingSymbol)
Assert.False(m2p4.HasExplicitDefaultValue)
Assert.False(m2p4.IsOptional)
Assert.True(m2p4.IsParamArray)
Assert.Equal(TypeKind.Array, m2p4.Type.TypeKind)
Assert.Equal("System.Object", DirectCast(m2p4.Type, ArrayTypeSymbol).ElementType.ToTestDisplayString())
Assert.Equal("System.Object()", m2p4.Type.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(1, m3.Parameters.Length)
Dim m3p1 = m3.Parameters(0)
Assert.Equal("x", m3p1.Name)
Assert.Same(m3, m3p1.ContainingSymbol)
Assert.False(m3p1.HasExplicitDefaultValue)
Assert.False(m3p1.IsOptional)
Assert.False(m3p1.IsParamArray)
Assert.Equal("System.Object", m3p1.Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodByRefParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Structure S
Function M(Byref x as Object, ByRef y As Byte) As Long
Return 0
End Function
End Structure
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim typeS = DirectCast(globalNS.GetTypeMembers("S").Single(), NamedTypeSymbol)
Dim m1 = DirectCast(typeS.GetMembers("M").Single(), MethodSymbol)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.True(m1p1.IsByRef)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Byte", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Byte", m1p2.ToTestDisplayString())
Assert.Equal("ValueType", m1p2.Type.BaseType.Name)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodTypeParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Partial Class C
Function m1(Of T, U)(x1 As T) As IEnumerable(Of U)
End Function
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(3, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.True(m1.IsGenericMethod)
Assert.Equal(2, m1.TypeParameters.Length)
Dim tpT = m1.TypeParameters(0)
Assert.Equal("T", tpT.Name)
Assert.Same(m1, tpT.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpT.Variance)
Dim tpU = m1.TypeParameters(1)
Assert.Equal("U", tpU.Name)
Assert.Same(m1, tpU.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpU.Variance)
Dim paramX1 = m1.Parameters(0)
Assert.Same(tpT, paramX1.Type)
Assert.Equal("T", paramX1.Type.ToTestDisplayString())
Assert.Same(tpU, DirectCast(m1.ReturnType, NamedTypeSymbol).TypeArguments(0))
Assert.Equal("System.Collections.Generic.IEnumerable(Of U)", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub ConstructGenericMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Class C(Of W)
Function m1(Of T, U)(p1 As T, p2 as W) As KeyValuePair(Of W, U))
End Function
Sub m2()
End Sub
Public Class D(Of X)
Sub m3(Of T)(p1 As T)
End Sub
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim constructedC = classC.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_Int32)}).AsImmutableOrNull())
Dim m1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Dim m2 = DirectCast(constructedC.GetMembers("m2")(0), MethodSymbol)
Assert.True(m1.CanConstruct)
Assert.True(m1.OriginalDefinition.CanConstruct)
Assert.Same(m1, m1.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.NotEqual(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0))
Assert.Same(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0).OriginalDefinition)
Assert.Same(m1, m1.TypeParameters(0).ContainingSymbol)
Assert.Equal(2, m1.Arity)
Assert.Same(m1, m1.Construct(m1.TypeParameters(0), m1.TypeParameters(1)))
Dim m1_1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Assert.Equal(m1, m1_1)
Assert.NotSame(m1, m1_1) ' Checks below need equal, but not identical symbols to test target scenarios!
Assert.Same(m1, m1.Construct(m1_1.TypeParameters(0), m1_1.TypeParameters(1)))
Dim alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(1), m1_1.TypeParameters(0))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(1))
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(0))
alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(0), constructedC)
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(0))
Assert.Same(alphaConstructedM1.TypeArguments(1), constructedC)
alphaConstructedM1 = m1.Construct(constructedC, m1_1.TypeParameters(1))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), constructedC)
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(1))
Assert.False(m2.CanConstruct)
Assert.False(m2.OriginalDefinition.CanConstruct)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.Throws(Of InvalidOperationException)(Sub() m2.OriginalDefinition.Construct(classC))
Assert.Throws(Of InvalidOperationException)(Sub() m2.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.OriginalDefinition.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.Construct(classC))
Dim constructedC_d = constructedC.GetTypeMembers("D").Single()
Dim m3 = DirectCast(constructedC_d.GetMembers("m3").Single(), MethodSymbol)
Assert.Equal(1, m3.Arity)
Assert.False(m3.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() m3.Construct(classC))
Dim d = classC.GetTypeMembers("D").Single()
m3 = DirectCast(d.GetMembers("m3").Single(), MethodSymbol)
Dim alphaConstructedM3 = m3.Construct(m1.TypeParameters(0))
Assert.NotSame(m3, alphaConstructedM3)
Assert.Same(m3, alphaConstructedM3.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), alphaConstructedM3.TypeArguments(0))
Assert.Equal("T", m1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", m1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, U)", m1.ReturnType.ToTestDisplayString())
Assert.Equal("T", m1.TypeParameters(0).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.Equal("U", m1.TypeParameters(1).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(1), m1.TypeArguments(1))
Assert.Same(m1, m1.ConstructedFrom)
Dim constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.Equal("System.String", constructedM1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", constructedM1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ReturnType.ToTestDisplayString())
Assert.Equal("T", constructedM1.TypeParameters(0).ToTestDisplayString())
Assert.Equal("System.String", constructedM1.TypeArguments(0).ToTestDisplayString())
Assert.Equal("U", constructedM1.TypeParameters(1).ToTestDisplayString())
Assert.Equal("System.Boolean", constructedM1.TypeArguments(1).ToTestDisplayString())
Assert.Same(m1, constructedM1.ConstructedFrom)
Assert.Equal("Function C(Of System.Int32).m1(Of System.String, System.Boolean)(p1 As System.String, p2 As System.Int32) As System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ToTestDisplayString())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
' Try wrong arity.
Assert.Throws(Of ArgumentException)(Sub()
Dim constructedM1WrongArity = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String)}).AsImmutableOrNull())
End Sub)
' Try identity substitution.
Dim identityM1 = m1.Construct(m1.OriginalDefinition.TypeParameters.As(Of TypeSymbol)())
Assert.NotEqual(m1, identityM1)
Assert.Same(m1, identityM1.ConstructedFrom)
m1 = DirectCast(classC.GetMembers("m1").Single(), MethodSymbol)
identityM1 = m1.Construct(m1.TypeParameters.As(Of TypeSymbol)())
Assert.Same(m1, identityM1)
constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
Dim constructedM1_2 = m1.Construct(compilation.GetSpecialType(SpecialType.System_Byte), compilation.GetSpecialType(SpecialType.System_Boolean))
Dim constructedM1_3 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.NotEqual(constructedM1, constructedM1_2)
Assert.Equal(constructedM1, constructedM1_3)
Dim p1 = constructedM1.Parameters(0)
Assert.Equal(0, p1.Ordinal)
Assert.Same(constructedM1, p1.ContainingSymbol)
Assert.Equal(p1, p1)
Assert.Equal(p1, constructedM1_3.Parameters(0))
Assert.Equal(p1.GetHashCode(), constructedM1_3.Parameters(0).GetHashCode())
Assert.NotEqual(m1.Parameters(0), p1)
Assert.NotEqual(constructedM1_2.Parameters(0), p1)
Dim constructedM3 = m3.Construct(compilation.GetSpecialType(SpecialType.System_String))
Assert.NotEqual(constructedM3.Parameters(0), p1)
End Sub
<Fact>
Public Sub InterfaceImplements01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Namespace NS
Public Class Abc
End Class
Public Interface IGoo(Of T)
Sub I1Sub1(ByRef p As T)
End Interface
Public Interface I1
Sub I1Sub1(ByRef p As String)
Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2 As Object()) As Integer
End Interface
Public Interface I2
Inherits I1
Sub I2Sub1()
Function I2Func1(ByRef p1 As aBC) As AbC
End Interface
End Namespace
</file>
<file name="b.vb">
Imports System.Collections.Generic
Namespace NS.NS1
Class Impl
Implements I2, IGoo(Of String)
Public Sub Sub1(ByRef p As String) Implements I1.I1Sub1, IGoo(Of String).I1Sub1
End Sub
Public Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2() As Object) As Integer Implements I1.I1Func1
Return p1
End Function
Public Function I2Func1(ByRef p1 As ABc) As ABC Implements I2.I2Func1
Return Nothing
End Function
Public Sub I2Sub1() Implements I2.I2Sub1
End Sub
End Class
Structure StructImpl(Of T)
Implements IGoo(Of T)
Public Sub Sub1(ByRef p As T) Implements IGoo(Of T).I1Sub1
End Sub
End Structure
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").AsEnumerable().SingleOrDefault(), NamespaceSymbol)
Dim ns1 = DirectCast(ns.GetMembers("NS1").Single(), NamespaceSymbol)
Dim classImpl = DirectCast(ns1.GetTypeMembers("impl").Single(), NamedTypeSymbol)
'direct interfaces
Assert.Equal(2, classImpl.Interfaces.Length)
Dim itfc = DirectCast(classImpl.Interfaces(0), NamedTypeSymbol)
Assert.Equal(1, itfc.Interfaces.Length)
itfc = DirectCast(itfc.Interfaces(0), NamedTypeSymbol)
Assert.Equal("I1", itfc.Name)
Dim mem1 = DirectCast(classImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(2, mem1.ExplicitInterfaceImplementation.Count)
mem1 = DirectCast(classImpl.GetMembers("i2Func1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count)
Dim param = DirectCast(mem1.Parameters(0), ParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal("ByRef " & param.Name & " As NS.Abc", param.ToTestDisplayString()) ' use case of declare's name
Dim structImpl = DirectCast(ns1.GetTypeMembers("structimpl").Single(), NamedTypeSymbol)
Assert.Equal(1, structImpl.Interfaces.Length)
Dim mem2 = DirectCast(structImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<WorkItem(537444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537444")>
<Fact>
Public Sub DeclareFunction01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Explicit
Imports System
Imports System.Runtime.InteropServices
Public Structure S1
Public strVar As String
Public x As Integer
End Structure
Namespace NS
Friend Module MyMod
Declare Ansi Function VerifyString2 Lib "AttrUsgOthM010DLL.dll" (ByRef Arg As S1, ByVal Op As Integer) As String
End Module
Class cls1
Overloads Declare Sub Goo Lib "someLib" ()
Overloads Sub goo(ByRef arg As Integer)
' ...
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim nsNS = DirectCast(compilation.Assembly.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim modOfNS = DirectCast(nsNS.GetMembers("MyMod").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(modOfNS.GetMembers().First(), MethodSymbol)
Assert.Equal("VerifyString2", mem1.Name)
' TODO: add more verification when this is working
End Sub
<Fact>
Public Sub CodepageOptionUnicodeMembers01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Module Module2
Sub ÛÊÛÄÁÍäá() ' 1067
Console.WriteLine (CStr(AscW("ÛÊÛÄÁÍäá")))
End Sub
End Module
Class Class1
Public Shared Sub ŒŸõ()
Console.WriteLine(CStr(AscW("ŒŸõ"))) ' 26908
End Sub
Friend Function [Widening](ByVal Ÿü As Short) As à–¾ 'invalid char in Dev10
Return New à–¾(Ÿü)
End Function
End Class
Structure ĵÁiÛE
Const str1 As String = "ĵÁiÛE" ' 1044
Dim i As Integer
End Structure
Public Class [Narrowing] 'êàê èäåíòèôèêàòîð.
Public ñëîâî As [CULng]
End Class
Public Structure [CULng]
Public [UInteger] As Integer
End Structure
</file>
</compilation>)
Dim glbNS = compilation.Assembly.GlobalNamespace
Dim type1 = DirectCast(glbNS.GetMembers("Module2").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(type1.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem1.DeclaredAccessibility)
Assert.True(mem1.IsSub)
Assert.Equal("Sub Module2.ÛÊÛÄÁÍäá()", mem1.ToTestDisplayString())
Dim type2 = DirectCast(glbNS.GetMembers("Class1").Single(), NamedTypeSymbol)
Dim mem2 = DirectCast(type2.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem2.DeclaredAccessibility)
'Assert.Equal("ŒŸõ", mem2.Name) - TODO: Code Page issue
Dim type3 = DirectCast(glbNS.GetTypeMembers("ĵÁiÛE").Single(), NamedTypeSymbol)
Dim mem3 = DirectCast(type3.GetMembers("Str1").Single(), FieldSymbol)
Assert.True(mem3.IsConst)
Assert.Equal("ĵÁiÛE.str1 As System.String", mem3.ToTestDisplayString())
Dim type4 = DirectCast(glbNS.GetTypeMembers("Narrowing").Single(), NamedTypeSymbol)
Dim mem4 = DirectCast(type4.GetMembers("ñëîâî").Single(), FieldSymbol)
Assert.Equal(TypeKind.Structure, mem4.Type.TypeKind)
End Sub
<WorkItem(537466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537466")>
<Fact>
Public Sub DefaultAccessibility01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Interface GI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class GC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Class
Structure GS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Structure
Namespace NS
Interface NI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class NC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Class
Structure NS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Structure
End Namespace
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
' interface - public
Dim typemem = DirectCast(globalNS.GetTypeMembers("GI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
Dim mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Class - field (private), other - public
typemem = DirectCast(globalNS.GetTypeMembers("GC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Struct - public
typemem = DirectCast(globalNS.GetTypeMembers("GS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
Dim nsNS = DirectCast(globalNS.GetMembers("NS").Single(), NamespaceSymbol)
typemem = DirectCast(nsNS.GetTypeMembers("NI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
End Sub
<Fact>
Public Sub OverloadsAndOverrides01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim derive = New NS.C2()
derive.Goo(1) ' call derived Goo
derive.Bar(1) ' call derived Bar
derive.Boo(1) ' call derived Boo
derive.VGoo(1) ' call derived VGoo
derive.VBar(1) ' call derived VBar
derive.VBoo(1) ' call derived VBoo
Console.WriteLine("-------------")
Dim base As NS.C1 = New NS.C2()
base.Goo(1) ' call base Goo
base.Bar(1) ' call base Bar
base.Boo(1) ' call base Boo
base.VGoo(1) ' call base Goo
base.VBar(1) ' call D
base.VBoo(1) ' call D
End Sub
End Module
Namespace NS
Public Class C1
Public Sub Goo(ByVal p As Integer)
Console.WriteLine("Base - Goo")
End Sub
Public Sub Bar(ByVal p As Integer)
Console.WriteLine("Base - Bar")
End Sub
Public Sub Boo(ByVal p As Integer)
Console.WriteLine("Base - Boo")
End Sub
Public Overridable Sub VGoo(ByVal p As Integer)
Console.WriteLine("Base - VGoo")
End Sub
Public Overridable Sub VBar(ByVal p As Integer)
Console.WriteLine("Base - VBar")
End Sub
Public Overridable Sub VBoo(ByVal p As Integer)
Console.WriteLine("Base - VBoo")
End Sub
End Class
Public Class C2
Inherits C1
Public Shadows Sub Goo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows Goo")
End Sub
Public Overloads Sub Bar(Optional ByVal p As Integer = 1)
Console.WriteLine("Derived - Overloads Bar")
End Sub
' warning
Public Sub Boo(Optional ByVal p As Integer = 2)
Console.WriteLine("Derived - Boo")
End Sub
' not virtual
Public Shadows Sub VGoo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows VGoo")
End Sub
' hidebysig and virtual
Public Overloads Overrides Sub VBar(ByVal p As Integer)
Console.WriteLine("Derived - Overloads Overrides VBar")
End Sub
' virtual
Public Overrides Sub VBoo(ByVal p As Integer)
Console.WriteLine("Derived - Overrides VBoo")
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetTypeMembers("C1").Single(), NamedTypeSymbol)
Dim mem = DirectCast(type1.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverridable)
mem = DirectCast(type1.GetMembers("VGoo").Single(), MethodSymbol)
Assert.True(mem.IsOverridable)
Dim type2 = DirectCast(ns.GetTypeMembers("C2").Single(), NamedTypeSymbol)
mem = DirectCast(type2.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Bar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Boo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
' overridable
mem = DirectCast(type2.GetMembers("VGoo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
Assert.False(mem.IsOverrides)
Assert.False(mem.IsOverridable)
mem = DirectCast(type2.GetMembers("VBar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
mem = DirectCast(type2.GetMembers("VBoo").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
End Sub
<Fact>
Public Sub Bug2820()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Class Class1
sub Test(x as T)
End sub
End Class
</file>
</compilation>)
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim test = class1.GetMembers("Test").OfType(Of MethodSymbol)().Single()
Assert.Equal("T", test.Parameters(0).Type.Name)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Sub baNana()
End Sub
Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Sub baNANa(xyz as String)
End Sub
Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' No "Overloads", so all methods should match first overloads in first source file
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNana").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNana" (from first file supplied to compilation).
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
If m.Parameters.Any Then
Assert.NotEqual("baNana", m.Name)
End If
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub baNANa(xyz as String)
End Sub
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overloads" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Overridable Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overrides Sub baNANa(xyz as String, a as integer)
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overrides" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BANANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, so all methods should match methods in base
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BAnANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, but base methods have multiple casing, so don't use it.
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "baNana".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub ProbableExtensionMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C">
<file name="a.vb">
Option Strict On
Class C1
Sub X()
goodext1()
goodext2()
goodext3()
goodext4()
goodext5()
goodext6()
goodext7()
goodext8()
badext1()
badext2()
badext3()
badext4()
badext5()
badext6()
End Sub
End Class
Namespace Blah
Class ExtensionAttribute
Inherits System.Attribute
End Class
End Namespace
</file>
<file name="b.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Runtime.CompilerServices
Imports ExAttribute = System.Runtime.CompilerServices.ExtensionAttribute
Imports Ex2 = System.Runtime.CompilerServices.ExtensionAttribute
Module M1
<[Extension]>
Public Sub goodext1(this As C1)
End Sub
<ExtensionAttribute>
Public Sub goodext2(this As C1)
End Sub
<System.Runtime.CompilerServices.Extension>
Public Sub goodext3(this As C1)
End Sub
<System.Runtime.CompilerServices.ExtensionAttribute>
Public Sub goodext4(this As C1)
End Sub
<[ExAttribute]>
Public Sub goodext5(this As C1)
End Sub
<Ex>
Public Sub goodext6(this As C1)
End Sub
<Ex2>
Public Sub goodext7(this As C1)
End Sub
<AnExt>
Public Sub goodext8(this As C1)
End Sub
<AnExt>
Declare Sub goodext9 Lib "goo" (this As C1)
<Blah.Extension>
Public Sub badext1(this As C1)
End Sub
<Blah.ExtensionAttribute>
Public Sub badext2(this As C1)
End Sub
<Extension>
Public Sub badext3()
End Sub
End Module
]]></file>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System
Imports Blah
Module M2
<Extension>
Public Sub badext4(this As C1)
End Sub
<ExtensionAttribute>
Public Sub badext5(this As C1)
End Sub
<Extension>
Declare Sub badext6 Lib "goo" (this As C1)
End Module
]]></file>
</compilation>, references:={TestMetadata.Net40.SystemCore, TestMetadata.Net40.System}, options:=TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse("AnExt=System.Runtime.CompilerServices.ExtensionAttribute")))
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim modM1 = DirectCast(globalNS.GetMembers("M1").Single(), NamedTypeSymbol)
Dim modM2 = DirectCast(globalNS.GetMembers("M2").Single(), NamedTypeSymbol)
Dim goodext1 = DirectCast(modM1.GetMembers("goodext1").Single(), MethodSymbol)
Assert.True(goodext1.IsExtensionMethod)
Assert.True(goodext1.MayBeReducibleExtensionMethod)
Dim goodext2 = DirectCast(modM1.GetMembers("goodext2").Single(), MethodSymbol)
Assert.True(goodext2.IsExtensionMethod)
Assert.True(goodext2.MayBeReducibleExtensionMethod)
Dim goodext3 = DirectCast(modM1.GetMembers("goodext3").Single(), MethodSymbol)
Assert.True(goodext3.IsExtensionMethod)
Assert.True(goodext3.MayBeReducibleExtensionMethod)
Dim goodext4 = DirectCast(modM1.GetMembers("goodext4").Single(), MethodSymbol)
Assert.True(goodext4.IsExtensionMethod)
Assert.True(goodext4.MayBeReducibleExtensionMethod)
Dim goodext5 = DirectCast(modM1.GetMembers("goodext5").Single(), MethodSymbol)
Assert.True(goodext5.IsExtensionMethod)
Assert.True(goodext5.MayBeReducibleExtensionMethod)
Dim goodext6 = DirectCast(modM1.GetMembers("goodext6").Single(), MethodSymbol)
Assert.True(goodext6.IsExtensionMethod)
Assert.True(goodext6.MayBeReducibleExtensionMethod)
Dim goodext7 = DirectCast(modM1.GetMembers("goodext7").Single(), MethodSymbol)
Assert.True(goodext7.IsExtensionMethod)
Assert.True(goodext7.MayBeReducibleExtensionMethod)
Dim goodext8 = DirectCast(modM1.GetMembers("goodext8").Single(), MethodSymbol)
Assert.True(goodext8.IsExtensionMethod)
Assert.True(goodext8.MayBeReducibleExtensionMethod)
Dim goodext9 = DirectCast(modM1.GetMembers("goodext9").Single(), MethodSymbol)
Assert.True(goodext9.IsExtensionMethod)
Assert.True(goodext9.MayBeReducibleExtensionMethod)
Dim badext1 = DirectCast(modM1.GetMembers("badext1").Single(), MethodSymbol)
Assert.False(badext1.IsExtensionMethod)
Assert.True(badext1.MayBeReducibleExtensionMethod)
Dim badext2 = DirectCast(modM1.GetMembers("badext2").Single(), MethodSymbol)
Assert.False(badext2.IsExtensionMethod)
Assert.True(badext2.MayBeReducibleExtensionMethod)
Dim badext3 = DirectCast(modM1.GetMembers("badext3").Single(), MethodSymbol)
Assert.False(badext3.IsExtensionMethod)
Assert.True(badext3.MayBeReducibleExtensionMethod)
Dim badext4 = DirectCast(modM2.GetMembers("badext4").Single(), MethodSymbol)
Assert.False(badext4.IsExtensionMethod)
Assert.True(badext4.MayBeReducibleExtensionMethod)
Dim badext5 = DirectCast(modM2.GetMembers("badext5").Single(), MethodSymbol)
Assert.False(badext5.IsExtensionMethod)
Assert.True(badext5.MayBeReducibleExtensionMethod)
Dim badext6 = DirectCast(modM2.GetMembers("badext6").Single(), MethodSymbol)
Assert.False(badext6.IsExtensionMethod)
Assert.True(badext6.MayBeReducibleExtensionMethod)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext1(this As C1)'.
badext1()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext2(this As C1)'.
badext2()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext4(this As C1)'.
badext4()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext5(this As C1)'.
badext5()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Declare Ansi Sub badext6 Lib "goo" (this As C1)'.
badext6()
~~~~~~~
BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend.
Public Sub badext3()
~~~~~~~
</expected>)
End Sub
<WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")>
<Fact>
Public Sub UserDefinedOperatorLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(c As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim operatorPos = source.IndexOf("+"c)
Dim parenPos = source.IndexOf("("c)
Dim comp = CreateCompilationWithMscorlib40({Parse(source)})
Dim Symbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single()
Dim span = Symbol.Locations.Single().SourceSpan
Assert.Equal(operatorPos, span.Start)
Assert.Equal(parenPos, span.End)
End Sub
<WorkItem(901815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/901815")>
<Fact>
Public Sub UserDefinedConversionLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(Of T)
Return Nothing
End Operator
End Class
]]>.Value
' Used to raise an exception.
Dim comp = CreateCompilationWithMscorlib40({Parse(source)}, options:=TestOptions.ReleaseDll)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC33016: Operator '+' must have either one or two parameters.
Public Shared Operator +(Of T)
~
BC30198: ')' expected.
Public Shared Operator +(Of T)
~
BC30199: '(' expected.
Public Shared Operator +(Of T)
~
BC32065: Type parameters cannot be specified on this declaration.
Public Shared Operator +(Of T)
~~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnNonPartial()
Dim source = <![CDATA[
Public Class C
Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.False(m.IsPartialDefinition)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnPartialDefinitionOnly()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.Null(m.PartialImplementationPart)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionWithPartialImplementation()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
Private Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.False(m.PartialImplementationPart.IsPartialDefinition)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicUnnecessaryImportsProvider.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.Formatting
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports
Friend NotInheritable Class VisualBasicUnnecessaryImportsProvider
Inherits AbstractUnnecessaryImportsProvider(Of ImportsClauseSyntax)
Public Shared Instance As New VisualBasicUnnecessaryImportsProvider
Private Sub New()
End Sub
Protected Overrides Function GetUnnecessaryImports(
model As SemanticModel, root As SyntaxNode,
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken) As ImmutableArray(Of SyntaxNode)
predicate = If(predicate, Functions(Of SyntaxNode).True)
Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken)
Dim unnecessaryImports = New HashSet(Of SyntaxNode)
For Each diagnostic In diagnostics
If diagnostic.Id = "BC50000" Then
Dim node = root.FindNode(diagnostic.Location.SourceSpan)
If node IsNot Nothing AndAlso predicate(node) Then
unnecessaryImports.Add(node)
End If
End If
If diagnostic.Id = "BC50001" Then
Dim node = TryCast(root.FindNode(diagnostic.Location.SourceSpan), ImportsStatementSyntax)
If node IsNot Nothing AndAlso predicate(node) Then
unnecessaryImports.AddRange(node.ImportsClauses)
End If
End If
Next
Dim oldRoot = DirectCast(root, CompilationUnitSyntax)
AddRedundantImports(oldRoot, model, unnecessaryImports, predicate, cancellationToken)
Return unnecessaryImports.ToImmutableArray()
End Function
Private Shared Sub AddRedundantImports(
compilationUnit As CompilationUnitSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of SyntaxNode),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
' Now that we've visited the tree, add any imports that bound to project level
' imports. We definitely can remove them.
For Each statement In compilationUnit.Imports
For Each clause In statement.ImportsClauses
cancellationToken.ThrowIfCancellationRequested()
Dim simpleImportsClause = TryCast(clause, SimpleImportsClauseSyntax)
If simpleImportsClause IsNot Nothing Then
If simpleImportsClause.Alias Is Nothing Then
AddRedundantMemberImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken)
Else
AddRedundantAliasImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken)
End If
End If
Next
Next
End Sub
Private Shared Sub AddRedundantAliasImportsClause(
clause As SimpleImportsClauseSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of SyntaxNode),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken)
Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol)
If namespaceOrType Is Nothing Then
Return
End If
Dim compilation = semanticModel.Compilation
Dim aliasSymbol = compilation.AliasImports.FirstOrDefault(Function(a) a.Name = clause.Alias.Identifier.ValueText)
If aliasSymbol IsNot Nothing AndAlso
aliasSymbol.Target.Equals(semanticInfo.Symbol) AndAlso
predicate(clause) Then
unnecessaryImports.Add(clause)
End If
End Sub
Private Shared Sub AddRedundantMemberImportsClause(
clause As SimpleImportsClauseSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of SyntaxNode),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken)
Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol)
If namespaceOrType Is Nothing Then
Return
End If
Dim compilation = semanticModel.Compilation
If compilation.MemberImports.Contains(namespaceOrType) AndAlso
predicate(clause) Then
unnecessaryImports.Add(clause)
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.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports
Friend NotInheritable Class VisualBasicUnnecessaryImportsProvider
Inherits AbstractUnnecessaryImportsProvider(Of ImportsClauseSyntax)
Public Shared Instance As New VisualBasicUnnecessaryImportsProvider
Private Sub New()
End Sub
Protected Overrides Function GetUnnecessaryImports(
model As SemanticModel, root As SyntaxNode,
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken) As ImmutableArray(Of SyntaxNode)
predicate = If(predicate, Functions(Of SyntaxNode).True)
Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken)
Dim unnecessaryImports = New HashSet(Of SyntaxNode)
For Each diagnostic In diagnostics
If diagnostic.Id = "BC50000" Then
Dim node = root.FindNode(diagnostic.Location.SourceSpan)
If node IsNot Nothing AndAlso predicate(node) Then
unnecessaryImports.Add(node)
End If
End If
If diagnostic.Id = "BC50001" Then
Dim node = TryCast(root.FindNode(diagnostic.Location.SourceSpan), ImportsStatementSyntax)
If node IsNot Nothing AndAlso predicate(node) Then
unnecessaryImports.AddRange(node.ImportsClauses)
End If
End If
Next
Dim oldRoot = DirectCast(root, CompilationUnitSyntax)
AddRedundantImports(oldRoot, model, unnecessaryImports, predicate, cancellationToken)
Return unnecessaryImports.ToImmutableArray()
End Function
Private Shared Sub AddRedundantImports(
compilationUnit As CompilationUnitSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of SyntaxNode),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
' Now that we've visited the tree, add any imports that bound to project level
' imports. We definitely can remove them.
For Each statement In compilationUnit.Imports
For Each clause In statement.ImportsClauses
cancellationToken.ThrowIfCancellationRequested()
Dim simpleImportsClause = TryCast(clause, SimpleImportsClauseSyntax)
If simpleImportsClause IsNot Nothing Then
If simpleImportsClause.Alias Is Nothing Then
AddRedundantMemberImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken)
Else
AddRedundantAliasImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken)
End If
End If
Next
Next
End Sub
Private Shared Sub AddRedundantAliasImportsClause(
clause As SimpleImportsClauseSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of SyntaxNode),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken)
Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol)
If namespaceOrType Is Nothing Then
Return
End If
Dim compilation = semanticModel.Compilation
Dim aliasSymbol = compilation.AliasImports.FirstOrDefault(Function(a) a.Name = clause.Alias.Identifier.ValueText)
If aliasSymbol IsNot Nothing AndAlso
aliasSymbol.Target.Equals(semanticInfo.Symbol) AndAlso
predicate(clause) Then
unnecessaryImports.Add(clause)
End If
End Sub
Private Shared Sub AddRedundantMemberImportsClause(
clause As SimpleImportsClauseSyntax,
semanticModel As SemanticModel,
unnecessaryImports As HashSet(Of SyntaxNode),
predicate As Func(Of SyntaxNode, Boolean),
cancellationToken As CancellationToken)
Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken)
Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol)
If namespaceOrType Is Nothing Then
Return
End If
Dim compilation = semanticModel.Compilation
If compilation.MemberImports.Contains(namespaceOrType) AndAlso
predicate(clause) Then
unnecessaryImports.Add(clause)
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/VisualBasic/Portable/Binding/BinderFactory.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.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The <see cref="BinderFactory"/> class finds the correct Binder to use for a node in a syntax
''' tree, down to method level. Within a method, the <see cref="ExecutableCodeBinder"/> has a
''' cache of further binders within the method.
'''
''' The <see cref="BinderFactory"/> caches results so that binders are efficiently reused between queries.
''' </summary>
Partial Friend Class BinderFactory
Private ReadOnly _sourceModule As SourceModuleSymbol
Private ReadOnly _tree As SyntaxTree
' Some syntax nodes, like method blocks, have multiple different binders associated with them
' for different parts of the method (the body, where parameters are available, and the header, where
' parameters aren't). To be able to cache a few different binders for each syntax node, we use
' a NodeUsage to sub-distinguish binders associated with nodes. Each kind of syntax node must have its
' associated usage value(s), because the usage is used when creating the binder (if not found in the cache).
Private ReadOnly _cache As ConcurrentDictionary(Of ValueTuple(Of VisualBasicSyntaxNode, Byte), Binder)
Private ReadOnly _binderFactoryVisitorPool As ObjectPool(Of BinderFactoryVisitor)
Private ReadOnly Property InScript As Boolean
Get
Return _tree.Options.Kind = SourceCodeKind.Script
End Get
End Property
Public Sub New(sourceModule As SourceModuleSymbol, tree As SyntaxTree)
Me._sourceModule = sourceModule
Me._tree = tree
Me._cache = New ConcurrentDictionary(Of ValueTuple(Of VisualBasicSyntaxNode, Byte), Binder)
Me._binderFactoryVisitorPool = New ObjectPool(Of BinderFactoryVisitor)(Function() New BinderFactoryVisitor(Me))
End Sub
Private Function MakeBinder(node As SyntaxNode, position As Integer) As Binder
If SyntaxFacts.InSpanOrEffectiveTrailingOfNode(node, position) OrElse
node.Kind = SyntaxKind.CompilationUnit Then
Dim visitor = _binderFactoryVisitorPool.Allocate()
visitor.Position = position
Dim result = visitor.Visit(node)
_binderFactoryVisitorPool.Free(visitor)
Return result
End If
Return Nothing
End Function
' Get binder for interior of a namespace block
Public Function GetNamespaceBinder(node As NamespaceBlockSyntax) As Binder
Return GetBinderForNodeAndUsage(node, NodeUsage.NamespaceBlockInterior, node.Parent, node.SpanStart)
End Function
' Get binder for a type
Public Function GetNamedTypeBinder(node As TypeStatementSyntax) As Binder
Dim possibleParentBlock = TryCast(node.Parent, TypeBlockSyntax)
Dim parentForEnclosingBinder As VisualBasicSyntaxNode = If(possibleParentBlock IsNot Nothing, possibleParentBlock.Parent, node.Parent)
Return GetBinderForNodeAndUsage(node, NodeUsage.TypeBlockFull, parentForEnclosingBinder, node.SpanStart)
End Function
' Get binder for an enum
Public Function GetNamedTypeBinder(node As EnumStatementSyntax) As Binder
Dim possibleParentBlock = TryCast(node.Parent, EnumBlockSyntax)
Dim parentForEnclosingBinder As VisualBasicSyntaxNode = If(possibleParentBlock IsNot Nothing, possibleParentBlock.Parent, node.Parent)
Return GetBinderForNodeAndUsage(node, NodeUsage.EnumBlockFull, parentForEnclosingBinder, node.SpanStart)
End Function
' Get binder for a delegate
Public Function GetNamedTypeBinder(node As DelegateStatementSyntax) As Binder
Return GetBinderForNodeAndUsage(node, NodeUsage.DelegateDeclaration, node.Parent, node.SpanStart)
End Function
' Find the binder to use for a position in the tree. The position should have been adjusted
' already to be at the start of a token.
Public Function GetBinderForPosition(node As SyntaxNode, position As Integer) As Binder
Return GetBinderAtOrAbove(node, position)
End Function
' Find the binder for a node or above at a given position
Private Function GetBinderAtOrAbove(node As SyntaxNode, position As Integer) As Binder
' Go up the tree until we find a node that has a corresponding binder.
Do
Dim binder As Binder = MakeBinder(node, position)
If binder IsNot Nothing Then
Return binder
End If
If node.Kind = SyntaxKind.DocumentationCommentTrivia Then
node = DirectCast(DirectCast(node, StructuredTriviaSyntax).ParentTrivia.Token.Parent, VisualBasicSyntaxNode)
Else
node = node.Parent
End If
' We should always find a binder, because the compilation unit should always give a binder,
' and going up the parent node chain should always get us a compilation unit.
Debug.Assert(node IsNot Nothing, "We should always get a binder")
Loop
End Function
' Given a node and usage, find the correct binder to use. Use the cache first, if not in the cache, then
' create a new binder. The parent node and position are used if we need to find an enclosing binder unless specified explicitly.
Private Function GetBinderForNodeAndUsage(node As VisualBasicSyntaxNode,
usage As NodeUsage,
Optional parentNode As VisualBasicSyntaxNode = Nothing,
Optional position As Integer = -1,
Optional containingBinder As Binder = Nothing) As Binder
' either parentNode and position is specified or the containingBinder is specified
Debug.Assert((parentNode Is Nothing) = (position < 0))
Debug.Assert(containingBinder Is Nothing OrElse parentNode Is Nothing)
Dim binder As Binder = Nothing
Dim nodeUsagePair = (node, CByte(usage))
If Not _cache.TryGetValue(nodeUsagePair, binder) Then
' Didn't find it in the cache, so we need to create it. But we need the containing binder first.
If containingBinder Is Nothing AndAlso parentNode IsNot Nothing Then
containingBinder = GetBinderAtOrAbove(parentNode, position)
End If
binder = CreateBinderForNodeAndUsage(node, usage, containingBinder)
_cache.TryAdd(nodeUsagePair, binder)
End If
Return binder
End Function
' Given a node, usage, and containing binder, create the binder for this node and usage. This is called
' only when we've found the given node & usage are not cached (and the caller will cache the result).
Private Function CreateBinderForNodeAndUsage(node As VisualBasicSyntaxNode,
usage As NodeUsage,
containingBinder As Binder) As Binder
Select Case usage
Case NodeUsage.CompilationUnit
' Get the binder associated with the default project namespace
Return BinderBuilder.CreateBinderForNamespace(_sourceModule, _tree, _sourceModule.RootNamespace)
Case NodeUsage.ImplicitClass
Dim implicitType As NamedTypeSymbol
If node.Kind <> SyntaxKind.CompilationUnit OrElse _tree.Options.Kind = SourceCodeKind.Regular Then
implicitType = DirectCast(containingBinder.ContainingNamespaceOrType.GetMembers(TypeSymbol.ImplicitTypeName).Single(), NamedTypeSymbol)
Else
implicitType = _sourceModule.ContainingSourceAssembly.DeclaringCompilation.SourceScriptClass
End If
Return New NamedTypeBinder(containingBinder, implicitType)
Case NodeUsage.ScriptCompilationUnit
Dim rootNamespaceBinder = GetBinderForNodeAndUsage(node, NodeUsage.CompilationUnit)
Debug.Assert(TypeOf rootNamespaceBinder Is NamespaceBinder)
' TODO (tomat): this is just a simple temporary solution, we'll need to plug-in submissions, interactive imports and host object members:
Return New NamedTypeBinder(rootNamespaceBinder, _sourceModule.ContainingSourceAssembly.DeclaringCompilation.SourceScriptClass)
Case NodeUsage.TopLevelExecutableStatement
Debug.Assert(TypeOf containingBinder Is NamedTypeBinder AndAlso containingBinder.ContainingType.IsScriptClass)
Return New TopLevelCodeBinder(containingBinder.ContainingType.InstanceConstructors.Single(), containingBinder)
Case NodeUsage.ImportsStatement
Return BinderBuilder.CreateBinderForSourceFileImports(_sourceModule, _tree)
Case NodeUsage.NamespaceBlockInterior
Dim nsBlockSyntax = DirectCast(node, NamespaceBlockSyntax)
Dim containingNamespaceBinder = TryCast(containingBinder, NamespaceBinder)
If containingNamespaceBinder Is Nothing Then
' If the containing binder is a script class binder use its namespace as a containing binder.
' It is an error
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing AndAlso containingNamedTypeBinder.ContainingType.IsScriptClass Then
Dim rootNamespaceBinder = GetBinderForNodeAndUsage(node, NodeUsage.CompilationUnit)
containingNamespaceBinder = DirectCast(rootNamespaceBinder, NamespaceBinder)
End If
End If
If containingNamespaceBinder IsNot Nothing Then
Return BuildNamespaceBinder(containingNamespaceBinder, nsBlockSyntax.NamespaceStatement.Name, nsBlockSyntax.Parent.Kind = SyntaxKind.CompilationUnit)
End If
Return containingBinder ' This occurs is some edge case error, like declaring a namespace inside a class.
Case NodeUsage.TypeBlockFull
Dim declarationSyntax = DirectCast(node, TypeStatementSyntax)
Dim symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(declarationSyntax,
containingBinder.ContainingNamespaceOrType,
_sourceModule)
' if symbol is invalid, we might be dealing with different error cases like class/namespace/class declaration
Return If(symbol IsNot Nothing, New NamedTypeBinder(containingBinder, symbol), containingBinder)
Case NodeUsage.EnumBlockFull
Dim declarationSyntax = DirectCast(node, EnumStatementSyntax)
Dim symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(declarationSyntax,
containingBinder.ContainingNamespaceOrType,
_sourceModule)
' if symbol is invalid, we might be dealing with different error cases like class/namespace/class declaration
Return If(symbol IsNot Nothing, New NamedTypeBinder(containingBinder, symbol), containingBinder)
Case NodeUsage.DelegateDeclaration
Dim delegateSyntax = DirectCast(node, DelegateStatementSyntax)
Dim symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(delegateSyntax,
containingBinder.ContainingNamespaceOrType,
_sourceModule)
' if symbol is invalid, we might be dealing with different error cases like class/namespace/class declaration
Return If(symbol IsNot Nothing, New NamedTypeBinder(containingBinder, symbol), containingBinder)
Case NodeUsage.InheritsStatement
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
' When binding the inherits clause, we don't want to look to base types of our own type, to follow how actual
' determination of the base type is done. This is done by using a BasesBeingResolvedBinder.
Debug.Assert(containingNamedTypeBinder.ContainingType IsNot Nothing)
Return New BasesBeingResolvedBinder(containingBinder, BasesBeingResolved.Empty.PrependInheritsBeingResolved(containingNamedTypeBinder.ContainingType))
Else
Return containingBinder
End If
Case NodeUsage.ImplementsStatement
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
Debug.Assert(containingNamedTypeBinder.ContainingType IsNot Nothing)
Return New BasesBeingResolvedBinder(containingBinder, BasesBeingResolved.Empty.PrependImplementsBeingResolved(containingNamedTypeBinder.ContainingType))
Else
Return containingBinder
End If
Case NodeUsage.PropertyFull
Return GetContainingNamedTypeBinderForMemberNode(DirectCast(node, PropertyStatementSyntax).Parent.Parent, containingBinder)
Case NodeUsage.MethodFull, NodeUsage.MethodInterior
Dim methodBase = DirectCast(node, MethodBaseSyntax)
Dim containingNamedTypeBinder = GetContainingNamedTypeBinderForMemberNode(node.Parent.Parent, containingBinder)
If containingNamedTypeBinder Is Nothing Then
Return containingBinder
End If
' UNDONE: Remove this once we can create MethodSymbols for other kinds of declarations.
Select Case methodBase.Kind
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.OperatorStatement
Case Else
Return containingBinder
End Select
Return BuildMethodBinder(containingNamedTypeBinder, methodBase, (usage = NodeUsage.MethodInterior))
Case NodeUsage.FieldOrPropertyInitializer
Dim fieldOrProperty As Symbol = Nothing
Dim additionalFieldsOrProperties = ImmutableArray(Of Symbol).Empty
Dim containingNamedTypeBinder As NamedTypeBinder
Select Case node.Kind
Case SyntaxKind.VariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
' Declaration should have initializer or AsNew.
Debug.Assert(declarator.Initializer IsNot Nothing OrElse TryCast(declarator.AsClause, AsNewClauseSyntax) IsNot Nothing)
' more than one name may happen if there is a syntax error or AsNew clause with multiple fields/properties
Debug.Assert(declarator.Names.Count > 0)
containingNamedTypeBinder = GetContainingNamedTypeBinderForMemberNode(node.Parent.Parent, containingBinder)
If containingNamedTypeBinder Is Nothing Then
Return Nothing
End If
Dim identifier = declarator.Names(0).Identifier
fieldOrProperty = containingNamedTypeBinder.ContainingType.FindFieldOrProperty(identifier.ValueText, identifier.Span, _tree)
' Handle multiple fields/properties initialized with AsNew clause
If declarator.Names.Count > 1 Then
Dim builder = ArrayBuilder(Of Symbol).GetInstance
For Each name In declarator.Names.Skip(1)
identifier = name.Identifier
Dim additionalFieldOrProperty As Symbol = containingNamedTypeBinder.ContainingType.FindFieldOrProperty(identifier.ValueText, identifier.Span, _tree)
builder.Add(additionalFieldOrProperty)
Next
additionalFieldsOrProperties = builder.ToImmutableAndFree
End If
Case SyntaxKind.EnumMemberDeclaration
Dim enumDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)
Debug.Assert(enumDeclaration.Initializer IsNot Nothing)
containingNamedTypeBinder = DirectCast(containingBinder, NamedTypeBinder)
Dim identifier = enumDeclaration.Identifier
fieldOrProperty = containingNamedTypeBinder.ContainingType.FindMember(identifier.ValueText, SymbolKind.Field, identifier.Span, _tree)
Case SyntaxKind.PropertyStatement
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
Debug.Assert(propertyStatement.Initializer IsNot Nothing OrElse TryCast(propertyStatement.AsClause, AsNewClauseSyntax) IsNot Nothing)
containingNamedTypeBinder = GetContainingNamedTypeBinderForMemberNode(node.Parent, containingBinder)
If containingNamedTypeBinder Is Nothing Then
Return Nothing
End If
Dim identifier = propertyStatement.Identifier
fieldOrProperty = containingNamedTypeBinder.ContainingType.FindMember(identifier.ValueText, SymbolKind.Property, identifier.Span, _tree)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
If fieldOrProperty IsNot Nothing Then
Return BuildInitializerBinder(containingNamedTypeBinder, fieldOrProperty, additionalFieldsOrProperties)
End If
Return Nothing
Case NodeUsage.FieldArrayBounds
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
Dim containingType = containingNamedTypeBinder.ContainingType
Dim identifier = modifiedIdentifier.Identifier
Dim field = containingType.FindMember(identifier.ValueText, SymbolKind.Field, identifier.Span, _tree)
If field IsNot Nothing Then
Return BuildInitializerBinder(containingNamedTypeBinder, field, ImmutableArray(Of Symbol).Empty)
End If
End If
Return Nothing
Case NodeUsage.Attribute
Return BuildAttributeBinder(containingBinder, node)
Case NodeUsage.ParameterDefaultValue
Dim parameterSyntax = DirectCast(node, ParameterSyntax)
If parameterSyntax.Default IsNot Nothing Then
Dim parameterListSyntax = DirectCast(parameterSyntax.Parent, ParameterListSyntax)
Dim methodSyntax = DirectCast(parameterListSyntax.Parent, MethodBaseSyntax)
Dim parameterSymbol As ParameterSymbol = Nothing
Select Case methodSyntax.Kind
Case SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.SubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing Then
Dim methodSymbol = DirectCast(SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType), SourceMethodSymbol)
If methodSymbol IsNot Nothing Then
parameterSymbol = GetParameterSymbol(methodSymbol.Parameters, parameterSyntax)
End If
End If
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing AndAlso
containingType.TypeKind = TypeKind.Delegate Then
Dim invokeSymbol = containingType.DelegateInvokeMethod
Debug.Assert(invokeSymbol IsNot Nothing, "Delegate should always have an invoke method.")
parameterSymbol = GetParameterSymbol(invokeSymbol.Parameters, parameterSyntax)
End If
Case SyntaxKind.EventStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing Then
Dim eventSymbol = DirectCast(SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType), SourceEventSymbol)
If eventSymbol IsNot Nothing Then
parameterSymbol = GetParameterSymbol(eventSymbol.DelegateParameters, parameterSyntax)
End If
End If
Case SyntaxKind.PropertyStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing Then
Dim propertySymbol = DirectCast(SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType), SourcePropertySymbol)
If propertySymbol IsNot Nothing Then
parameterSymbol = GetParameterSymbol(propertySymbol.Parameters, parameterSyntax)
End If
End If
Case SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' Default values are not valid (and not bound) for lambda parameters or property accessors
Return Nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(methodSyntax.Kind)
End Select
If parameterSymbol IsNot Nothing Then
Return BinderBuilder.CreateBinderForParameterDefaultValue(parameterSymbol, containingBinder, parameterSyntax)
End If
End If
Return Nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(usage)
End Select
End Function
Private Function CreateDocumentationCommentBinder(node As DocumentationCommentTriviaSyntax, binderType As DocumentationCommentBinder.BinderType) As Binder
Debug.Assert(binderType <> DocumentationCommentBinder.BinderType.None)
' Now we need to find a symbol for class/structure, method, event, or property
' Those may be needed to bind parameters and/or type parameters
' Note that we actually don't need field/module/enum symbols, because they
' do not have type parameters or parameters
Dim trivia As SyntaxTrivia = node.ParentTrivia
Dim token As SyntaxToken = CType(trivia.Token, SyntaxToken)
Dim parent = DirectCast(token.Parent, VisualBasicSyntaxNode)
Debug.Assert(parent IsNot Nothing)
' This is a binder for commented symbol's containing type or namespace
Dim nodeForOuterBinder As VisualBasicSyntaxNode = Nothing
lAgain:
Select Case parent.Kind
Case SyntaxKind.ClassStatement,
SyntaxKind.EnumStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.StructureStatement,
SyntaxKind.ModuleStatement
' BREAK: Roslyn uses the type binder, whereas Dev11 uses the scope strictly above the type declaration.
' This change was made to improve the consistency with C#. In particular, it allows unqualified references
' to members of the type to which the doc comment has been applied.
nodeForOuterBinder = parent
Case SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.OperatorStatement
' Delegates don't have user-defined members, so it makes more sense to treat
' them like methods.
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing AndAlso TypeOf (nodeForOuterBinder) Is MethodBlockBaseSyntax Then
nodeForOuterBinder = nodeForOuterBinder.Parent
End If
Case SyntaxKind.PropertyStatement
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing AndAlso nodeForOuterBinder.Kind = SyntaxKind.PropertyBlock Then
nodeForOuterBinder = nodeForOuterBinder.Parent
End If
Case SyntaxKind.EventStatement
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing AndAlso nodeForOuterBinder.Kind = SyntaxKind.EventStatement Then
nodeForOuterBinder = nodeForOuterBinder.Parent
End If
Case SyntaxKind.FieldDeclaration,
SyntaxKind.EnumMemberDeclaration
nodeForOuterBinder = parent.Parent
Case SyntaxKind.AttributeList
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing Then
parent = nodeForOuterBinder
nodeForOuterBinder = Nothing
GoTo lAgain
End If
End Select
If nodeForOuterBinder Is Nothing Then
Return GetBinderAtOrAbove(parent, parent.SpanStart)
End If
Dim containingBinder As Binder = GetBinderAtOrAbove(nodeForOuterBinder, parent.SpanStart)
Dim symbol As Symbol = Nothing
Select Case parent.Kind
Case SyntaxKind.ClassStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.StructureStatement
symbol = containingBinder.ContainingNamespaceOrType
Case SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.PropertyStatement,
SyntaxKind.EventStatement
If containingBinder.ContainingType IsNot Nothing Then
symbol = SourceMethodSymbol.FindSymbolFromSyntax(
DirectCast(parent, MethodBaseSyntax), _tree, containingBinder.ContainingType)
End If
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
If containingBinder.ContainingType IsNot Nothing Then
symbol = SourceMethodSymbol.FindSymbolFromSyntax(
DirectCast(parent, MethodBaseSyntax), _tree, containingBinder.ContainingType)
Else
symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(
DirectCast(parent, DelegateStatementSyntax), containingBinder.ContainingNamespaceOrType, _sourceModule)
End If
Case SyntaxKind.FieldDeclaration,
SyntaxKind.EnumStatement,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.ModuleStatement
' we are not using field, enum, module symbols for params or type params resolution
Case Else
Throw ExceptionUtilities.UnexpectedValue(parent.Kind)
End Select
Return BinderBuilder.CreateBinderForDocumentationComment(containingBinder, symbol, binderType)
End Function
Private Function GetContainingNamedTypeBinderForMemberNode(node As VisualBasicSyntaxNode, containingBinder As Binder) As NamedTypeBinder
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
Return containingNamedTypeBinder
End If
' member declared on top-level or in a namespace is enclosed in an implicit type:
If node IsNot Nothing AndAlso (node.Kind = SyntaxKind.NamespaceBlock OrElse node.Kind = SyntaxKind.CompilationUnit) Then
Return DirectCast(
GetBinderForNodeAndUsage(node, NodeUsage.ImplicitClass,
containingBinder:=containingBinder), NamedTypeBinder)
End If
Return Nothing
End Function
Private Shared Function GetParameterDeclarationContainingType(containingBinder As Binder) As NamedTypeSymbol
' Method declarations are bound using either a NamedTypeBinder or a MethodTypeParametersBinder
Dim namedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If namedTypeBinder Is Nothing Then
' Must be a MethodTypeParametersBinder unless the member
' containing the parameter is outside of a type (in invalid code).
Dim methodDeclarationBinder = TryCast(containingBinder, MethodTypeParametersBinder)
If methodDeclarationBinder Is Nothing Then
Return Nothing
End If
namedTypeBinder = DirectCast(methodDeclarationBinder.ContainingBinder, NamedTypeBinder)
End If
Return namedTypeBinder.ContainingType
End Function
' Given the name of a child namespace, build up a binder from a containing binder.
Private Function BuildNamespaceBinder(containingBinder As NamespaceBinder, childName As NameSyntax, globalNamespaceAllowed As Boolean) As NamespaceBinder
Dim name As String
Select Case childName.Kind
Case SyntaxKind.GlobalName
If globalNamespaceAllowed Then
Return DirectCast(BinderBuilder.CreateBinderForNamespace(_sourceModule, _tree, _sourceModule.GlobalNamespace), NamespaceBinder)
Else
' Global namespace isn't allowed here. Use a namespace named "Global" as error recovery (see corresponding code in DeclarationTreeBuilder)
name = "Global"
End If
Case SyntaxKind.QualifiedName
Dim dotted = DirectCast(childName, QualifiedNameSyntax)
containingBinder = BuildNamespaceBinder(containingBinder, dotted.Left, globalNamespaceAllowed)
name = dotted.Right.Identifier.ValueText
Case SyntaxKind.IdentifierName
name = DirectCast(childName, IdentifierNameSyntax).Identifier.ValueText
Case Else
Throw ExceptionUtilities.UnexpectedValue(childName.Kind)
End Select
For Each symbol As NamespaceOrTypeSymbol In containingBinder.NamespaceSymbol.GetMembers(name)
Dim nsChild = TryCast(symbol, NamespaceSymbol)
If nsChild IsNot Nothing Then
Return New NamespaceBinder(containingBinder, nsChild)
End If
Next
' Namespace is expected to be found by name in parent binder.
Throw ExceptionUtilities.Unreachable
End Function
' Given the name of a method, and the span of the name, and the containing type binder, get the
' binder for the method. We just search all the method symbols with the given name.
Private Function BuildMethodBinder(containingBinder As NamedTypeBinder,
methodSyntax As MethodBaseSyntax,
forBody As Boolean) As Binder
Dim containingType = containingBinder.ContainingType
Dim symbol = SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType)
If (symbol IsNot Nothing) AndAlso
(symbol.Kind = SymbolKind.Method) Then
Dim methodSymbol = DirectCast(symbol, SourceMethodSymbol)
If forBody Then
Return BinderBuilder.CreateBinderForMethodBody(methodSymbol, methodSymbol.Syntax, containingBinder)
Else
Return BinderBuilder.CreateBinderForMethodDeclaration(methodSymbol, containingBinder)
End If
Else
' Not sure if there's a case where we get here. For now, fail. Maybe if a declarations
' is so malformed there isn't a symbol for it?
' This can happen if property has multiple accessors.
' Parser allows multiple accessors, but binder will accept only one of a kind
Return containingBinder
End If
End Function
Private Function BuildInitializerBinder(containingBinder As Binder, fieldOrProperty As Symbol, additionalFieldsOrProperties As ImmutableArray(Of Symbol)) As Binder
Return BinderBuilder.CreateBinderForInitializer(containingBinder, fieldOrProperty, additionalFieldsOrProperties)
End Function
Private Function BuildAttributeBinder(containingBinder As Binder, node As VisualBasicSyntaxNode) As Binder
Debug.Assert(node.Kind = SyntaxKind.Attribute)
If containingBinder IsNot Nothing AndAlso node.Parent IsNot Nothing Then
' Go to attribute block
Dim attributeBlock = node.Parent
' Go to statement that owns the attribute
If attributeBlock.Parent IsNot Nothing Then
Select Case attributeBlock.Parent.Kind
Case SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.EnumStatement
' Attributes on a class, module, structure, interface, or enum are contained within those nodes. However, the members of those
' blocks should not be in scope when evaluating expressions within the attribute. Therefore, remove the named type binder from
' the binder hierarchy.
If TypeOf containingBinder Is NamedTypeBinder Then
containingBinder = containingBinder.ContainingBinder
End If
End Select
End If
End If
Return BinderBuilder.CreateBinderForAttribute(_tree, containingBinder, node)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The <see cref="BinderFactory"/> class finds the correct Binder to use for a node in a syntax
''' tree, down to method level. Within a method, the <see cref="ExecutableCodeBinder"/> has a
''' cache of further binders within the method.
'''
''' The <see cref="BinderFactory"/> caches results so that binders are efficiently reused between queries.
''' </summary>
Partial Friend Class BinderFactory
Private ReadOnly _sourceModule As SourceModuleSymbol
Private ReadOnly _tree As SyntaxTree
' Some syntax nodes, like method blocks, have multiple different binders associated with them
' for different parts of the method (the body, where parameters are available, and the header, where
' parameters aren't). To be able to cache a few different binders for each syntax node, we use
' a NodeUsage to sub-distinguish binders associated with nodes. Each kind of syntax node must have its
' associated usage value(s), because the usage is used when creating the binder (if not found in the cache).
Private ReadOnly _cache As ConcurrentDictionary(Of ValueTuple(Of VisualBasicSyntaxNode, Byte), Binder)
Private ReadOnly _binderFactoryVisitorPool As ObjectPool(Of BinderFactoryVisitor)
Private ReadOnly Property InScript As Boolean
Get
Return _tree.Options.Kind = SourceCodeKind.Script
End Get
End Property
Public Sub New(sourceModule As SourceModuleSymbol, tree As SyntaxTree)
Me._sourceModule = sourceModule
Me._tree = tree
Me._cache = New ConcurrentDictionary(Of ValueTuple(Of VisualBasicSyntaxNode, Byte), Binder)
Me._binderFactoryVisitorPool = New ObjectPool(Of BinderFactoryVisitor)(Function() New BinderFactoryVisitor(Me))
End Sub
Private Function MakeBinder(node As SyntaxNode, position As Integer) As Binder
If SyntaxFacts.InSpanOrEffectiveTrailingOfNode(node, position) OrElse
node.Kind = SyntaxKind.CompilationUnit Then
Dim visitor = _binderFactoryVisitorPool.Allocate()
visitor.Position = position
Dim result = visitor.Visit(node)
_binderFactoryVisitorPool.Free(visitor)
Return result
End If
Return Nothing
End Function
' Get binder for interior of a namespace block
Public Function GetNamespaceBinder(node As NamespaceBlockSyntax) As Binder
Return GetBinderForNodeAndUsage(node, NodeUsage.NamespaceBlockInterior, node.Parent, node.SpanStart)
End Function
' Get binder for a type
Public Function GetNamedTypeBinder(node As TypeStatementSyntax) As Binder
Dim possibleParentBlock = TryCast(node.Parent, TypeBlockSyntax)
Dim parentForEnclosingBinder As VisualBasicSyntaxNode = If(possibleParentBlock IsNot Nothing, possibleParentBlock.Parent, node.Parent)
Return GetBinderForNodeAndUsage(node, NodeUsage.TypeBlockFull, parentForEnclosingBinder, node.SpanStart)
End Function
' Get binder for an enum
Public Function GetNamedTypeBinder(node As EnumStatementSyntax) As Binder
Dim possibleParentBlock = TryCast(node.Parent, EnumBlockSyntax)
Dim parentForEnclosingBinder As VisualBasicSyntaxNode = If(possibleParentBlock IsNot Nothing, possibleParentBlock.Parent, node.Parent)
Return GetBinderForNodeAndUsage(node, NodeUsage.EnumBlockFull, parentForEnclosingBinder, node.SpanStart)
End Function
' Get binder for a delegate
Public Function GetNamedTypeBinder(node As DelegateStatementSyntax) As Binder
Return GetBinderForNodeAndUsage(node, NodeUsage.DelegateDeclaration, node.Parent, node.SpanStart)
End Function
' Find the binder to use for a position in the tree. The position should have been adjusted
' already to be at the start of a token.
Public Function GetBinderForPosition(node As SyntaxNode, position As Integer) As Binder
Return GetBinderAtOrAbove(node, position)
End Function
' Find the binder for a node or above at a given position
Private Function GetBinderAtOrAbove(node As SyntaxNode, position As Integer) As Binder
' Go up the tree until we find a node that has a corresponding binder.
Do
Dim binder As Binder = MakeBinder(node, position)
If binder IsNot Nothing Then
Return binder
End If
If node.Kind = SyntaxKind.DocumentationCommentTrivia Then
node = DirectCast(DirectCast(node, StructuredTriviaSyntax).ParentTrivia.Token.Parent, VisualBasicSyntaxNode)
Else
node = node.Parent
End If
' We should always find a binder, because the compilation unit should always give a binder,
' and going up the parent node chain should always get us a compilation unit.
Debug.Assert(node IsNot Nothing, "We should always get a binder")
Loop
End Function
' Given a node and usage, find the correct binder to use. Use the cache first, if not in the cache, then
' create a new binder. The parent node and position are used if we need to find an enclosing binder unless specified explicitly.
Private Function GetBinderForNodeAndUsage(node As VisualBasicSyntaxNode,
usage As NodeUsage,
Optional parentNode As VisualBasicSyntaxNode = Nothing,
Optional position As Integer = -1,
Optional containingBinder As Binder = Nothing) As Binder
' either parentNode and position is specified or the containingBinder is specified
Debug.Assert((parentNode Is Nothing) = (position < 0))
Debug.Assert(containingBinder Is Nothing OrElse parentNode Is Nothing)
Dim binder As Binder = Nothing
Dim nodeUsagePair = (node, CByte(usage))
If Not _cache.TryGetValue(nodeUsagePair, binder) Then
' Didn't find it in the cache, so we need to create it. But we need the containing binder first.
If containingBinder Is Nothing AndAlso parentNode IsNot Nothing Then
containingBinder = GetBinderAtOrAbove(parentNode, position)
End If
binder = CreateBinderForNodeAndUsage(node, usage, containingBinder)
_cache.TryAdd(nodeUsagePair, binder)
End If
Return binder
End Function
' Given a node, usage, and containing binder, create the binder for this node and usage. This is called
' only when we've found the given node & usage are not cached (and the caller will cache the result).
Private Function CreateBinderForNodeAndUsage(node As VisualBasicSyntaxNode,
usage As NodeUsage,
containingBinder As Binder) As Binder
Select Case usage
Case NodeUsage.CompilationUnit
' Get the binder associated with the default project namespace
Return BinderBuilder.CreateBinderForNamespace(_sourceModule, _tree, _sourceModule.RootNamespace)
Case NodeUsage.ImplicitClass
Dim implicitType As NamedTypeSymbol
If node.Kind <> SyntaxKind.CompilationUnit OrElse _tree.Options.Kind = SourceCodeKind.Regular Then
implicitType = DirectCast(containingBinder.ContainingNamespaceOrType.GetMembers(TypeSymbol.ImplicitTypeName).Single(), NamedTypeSymbol)
Else
implicitType = _sourceModule.ContainingSourceAssembly.DeclaringCompilation.SourceScriptClass
End If
Return New NamedTypeBinder(containingBinder, implicitType)
Case NodeUsage.ScriptCompilationUnit
Dim rootNamespaceBinder = GetBinderForNodeAndUsage(node, NodeUsage.CompilationUnit)
Debug.Assert(TypeOf rootNamespaceBinder Is NamespaceBinder)
' TODO (tomat): this is just a simple temporary solution, we'll need to plug-in submissions, interactive imports and host object members:
Return New NamedTypeBinder(rootNamespaceBinder, _sourceModule.ContainingSourceAssembly.DeclaringCompilation.SourceScriptClass)
Case NodeUsage.TopLevelExecutableStatement
Debug.Assert(TypeOf containingBinder Is NamedTypeBinder AndAlso containingBinder.ContainingType.IsScriptClass)
Return New TopLevelCodeBinder(containingBinder.ContainingType.InstanceConstructors.Single(), containingBinder)
Case NodeUsage.ImportsStatement
Return BinderBuilder.CreateBinderForSourceFileImports(_sourceModule, _tree)
Case NodeUsage.NamespaceBlockInterior
Dim nsBlockSyntax = DirectCast(node, NamespaceBlockSyntax)
Dim containingNamespaceBinder = TryCast(containingBinder, NamespaceBinder)
If containingNamespaceBinder Is Nothing Then
' If the containing binder is a script class binder use its namespace as a containing binder.
' It is an error
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing AndAlso containingNamedTypeBinder.ContainingType.IsScriptClass Then
Dim rootNamespaceBinder = GetBinderForNodeAndUsage(node, NodeUsage.CompilationUnit)
containingNamespaceBinder = DirectCast(rootNamespaceBinder, NamespaceBinder)
End If
End If
If containingNamespaceBinder IsNot Nothing Then
Return BuildNamespaceBinder(containingNamespaceBinder, nsBlockSyntax.NamespaceStatement.Name, nsBlockSyntax.Parent.Kind = SyntaxKind.CompilationUnit)
End If
Return containingBinder ' This occurs is some edge case error, like declaring a namespace inside a class.
Case NodeUsage.TypeBlockFull
Dim declarationSyntax = DirectCast(node, TypeStatementSyntax)
Dim symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(declarationSyntax,
containingBinder.ContainingNamespaceOrType,
_sourceModule)
' if symbol is invalid, we might be dealing with different error cases like class/namespace/class declaration
Return If(symbol IsNot Nothing, New NamedTypeBinder(containingBinder, symbol), containingBinder)
Case NodeUsage.EnumBlockFull
Dim declarationSyntax = DirectCast(node, EnumStatementSyntax)
Dim symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(declarationSyntax,
containingBinder.ContainingNamespaceOrType,
_sourceModule)
' if symbol is invalid, we might be dealing with different error cases like class/namespace/class declaration
Return If(symbol IsNot Nothing, New NamedTypeBinder(containingBinder, symbol), containingBinder)
Case NodeUsage.DelegateDeclaration
Dim delegateSyntax = DirectCast(node, DelegateStatementSyntax)
Dim symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(delegateSyntax,
containingBinder.ContainingNamespaceOrType,
_sourceModule)
' if symbol is invalid, we might be dealing with different error cases like class/namespace/class declaration
Return If(symbol IsNot Nothing, New NamedTypeBinder(containingBinder, symbol), containingBinder)
Case NodeUsage.InheritsStatement
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
' When binding the inherits clause, we don't want to look to base types of our own type, to follow how actual
' determination of the base type is done. This is done by using a BasesBeingResolvedBinder.
Debug.Assert(containingNamedTypeBinder.ContainingType IsNot Nothing)
Return New BasesBeingResolvedBinder(containingBinder, BasesBeingResolved.Empty.PrependInheritsBeingResolved(containingNamedTypeBinder.ContainingType))
Else
Return containingBinder
End If
Case NodeUsage.ImplementsStatement
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
Debug.Assert(containingNamedTypeBinder.ContainingType IsNot Nothing)
Return New BasesBeingResolvedBinder(containingBinder, BasesBeingResolved.Empty.PrependImplementsBeingResolved(containingNamedTypeBinder.ContainingType))
Else
Return containingBinder
End If
Case NodeUsage.PropertyFull
Return GetContainingNamedTypeBinderForMemberNode(DirectCast(node, PropertyStatementSyntax).Parent.Parent, containingBinder)
Case NodeUsage.MethodFull, NodeUsage.MethodInterior
Dim methodBase = DirectCast(node, MethodBaseSyntax)
Dim containingNamedTypeBinder = GetContainingNamedTypeBinderForMemberNode(node.Parent.Parent, containingBinder)
If containingNamedTypeBinder Is Nothing Then
Return containingBinder
End If
' UNDONE: Remove this once we can create MethodSymbols for other kinds of declarations.
Select Case methodBase.Kind
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.OperatorStatement
Case Else
Return containingBinder
End Select
Return BuildMethodBinder(containingNamedTypeBinder, methodBase, (usage = NodeUsage.MethodInterior))
Case NodeUsage.FieldOrPropertyInitializer
Dim fieldOrProperty As Symbol = Nothing
Dim additionalFieldsOrProperties = ImmutableArray(Of Symbol).Empty
Dim containingNamedTypeBinder As NamedTypeBinder
Select Case node.Kind
Case SyntaxKind.VariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
' Declaration should have initializer or AsNew.
Debug.Assert(declarator.Initializer IsNot Nothing OrElse TryCast(declarator.AsClause, AsNewClauseSyntax) IsNot Nothing)
' more than one name may happen if there is a syntax error or AsNew clause with multiple fields/properties
Debug.Assert(declarator.Names.Count > 0)
containingNamedTypeBinder = GetContainingNamedTypeBinderForMemberNode(node.Parent.Parent, containingBinder)
If containingNamedTypeBinder Is Nothing Then
Return Nothing
End If
Dim identifier = declarator.Names(0).Identifier
fieldOrProperty = containingNamedTypeBinder.ContainingType.FindFieldOrProperty(identifier.ValueText, identifier.Span, _tree)
' Handle multiple fields/properties initialized with AsNew clause
If declarator.Names.Count > 1 Then
Dim builder = ArrayBuilder(Of Symbol).GetInstance
For Each name In declarator.Names.Skip(1)
identifier = name.Identifier
Dim additionalFieldOrProperty As Symbol = containingNamedTypeBinder.ContainingType.FindFieldOrProperty(identifier.ValueText, identifier.Span, _tree)
builder.Add(additionalFieldOrProperty)
Next
additionalFieldsOrProperties = builder.ToImmutableAndFree
End If
Case SyntaxKind.EnumMemberDeclaration
Dim enumDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)
Debug.Assert(enumDeclaration.Initializer IsNot Nothing)
containingNamedTypeBinder = DirectCast(containingBinder, NamedTypeBinder)
Dim identifier = enumDeclaration.Identifier
fieldOrProperty = containingNamedTypeBinder.ContainingType.FindMember(identifier.ValueText, SymbolKind.Field, identifier.Span, _tree)
Case SyntaxKind.PropertyStatement
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
Debug.Assert(propertyStatement.Initializer IsNot Nothing OrElse TryCast(propertyStatement.AsClause, AsNewClauseSyntax) IsNot Nothing)
containingNamedTypeBinder = GetContainingNamedTypeBinderForMemberNode(node.Parent, containingBinder)
If containingNamedTypeBinder Is Nothing Then
Return Nothing
End If
Dim identifier = propertyStatement.Identifier
fieldOrProperty = containingNamedTypeBinder.ContainingType.FindMember(identifier.ValueText, SymbolKind.Property, identifier.Span, _tree)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
If fieldOrProperty IsNot Nothing Then
Return BuildInitializerBinder(containingNamedTypeBinder, fieldOrProperty, additionalFieldsOrProperties)
End If
Return Nothing
Case NodeUsage.FieldArrayBounds
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
Dim containingType = containingNamedTypeBinder.ContainingType
Dim identifier = modifiedIdentifier.Identifier
Dim field = containingType.FindMember(identifier.ValueText, SymbolKind.Field, identifier.Span, _tree)
If field IsNot Nothing Then
Return BuildInitializerBinder(containingNamedTypeBinder, field, ImmutableArray(Of Symbol).Empty)
End If
End If
Return Nothing
Case NodeUsage.Attribute
Return BuildAttributeBinder(containingBinder, node)
Case NodeUsage.ParameterDefaultValue
Dim parameterSyntax = DirectCast(node, ParameterSyntax)
If parameterSyntax.Default IsNot Nothing Then
Dim parameterListSyntax = DirectCast(parameterSyntax.Parent, ParameterListSyntax)
Dim methodSyntax = DirectCast(parameterListSyntax.Parent, MethodBaseSyntax)
Dim parameterSymbol As ParameterSymbol = Nothing
Select Case methodSyntax.Kind
Case SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.SubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing Then
Dim methodSymbol = DirectCast(SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType), SourceMethodSymbol)
If methodSymbol IsNot Nothing Then
parameterSymbol = GetParameterSymbol(methodSymbol.Parameters, parameterSyntax)
End If
End If
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing AndAlso
containingType.TypeKind = TypeKind.Delegate Then
Dim invokeSymbol = containingType.DelegateInvokeMethod
Debug.Assert(invokeSymbol IsNot Nothing, "Delegate should always have an invoke method.")
parameterSymbol = GetParameterSymbol(invokeSymbol.Parameters, parameterSyntax)
End If
Case SyntaxKind.EventStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing Then
Dim eventSymbol = DirectCast(SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType), SourceEventSymbol)
If eventSymbol IsNot Nothing Then
parameterSymbol = GetParameterSymbol(eventSymbol.DelegateParameters, parameterSyntax)
End If
End If
Case SyntaxKind.PropertyStatement
Dim containingType = GetParameterDeclarationContainingType(containingBinder)
If containingType IsNot Nothing Then
Dim propertySymbol = DirectCast(SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType), SourcePropertySymbol)
If propertySymbol IsNot Nothing Then
parameterSymbol = GetParameterSymbol(propertySymbol.Parameters, parameterSyntax)
End If
End If
Case SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' Default values are not valid (and not bound) for lambda parameters or property accessors
Return Nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(methodSyntax.Kind)
End Select
If parameterSymbol IsNot Nothing Then
Return BinderBuilder.CreateBinderForParameterDefaultValue(parameterSymbol, containingBinder, parameterSyntax)
End If
End If
Return Nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(usage)
End Select
End Function
Private Function CreateDocumentationCommentBinder(node As DocumentationCommentTriviaSyntax, binderType As DocumentationCommentBinder.BinderType) As Binder
Debug.Assert(binderType <> DocumentationCommentBinder.BinderType.None)
' Now we need to find a symbol for class/structure, method, event, or property
' Those may be needed to bind parameters and/or type parameters
' Note that we actually don't need field/module/enum symbols, because they
' do not have type parameters or parameters
Dim trivia As SyntaxTrivia = node.ParentTrivia
Dim token As SyntaxToken = CType(trivia.Token, SyntaxToken)
Dim parent = DirectCast(token.Parent, VisualBasicSyntaxNode)
Debug.Assert(parent IsNot Nothing)
' This is a binder for commented symbol's containing type or namespace
Dim nodeForOuterBinder As VisualBasicSyntaxNode = Nothing
lAgain:
Select Case parent.Kind
Case SyntaxKind.ClassStatement,
SyntaxKind.EnumStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.StructureStatement,
SyntaxKind.ModuleStatement
' BREAK: Roslyn uses the type binder, whereas Dev11 uses the scope strictly above the type declaration.
' This change was made to improve the consistency with C#. In particular, it allows unqualified references
' to members of the type to which the doc comment has been applied.
nodeForOuterBinder = parent
Case SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.OperatorStatement
' Delegates don't have user-defined members, so it makes more sense to treat
' them like methods.
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing AndAlso TypeOf (nodeForOuterBinder) Is MethodBlockBaseSyntax Then
nodeForOuterBinder = nodeForOuterBinder.Parent
End If
Case SyntaxKind.PropertyStatement
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing AndAlso nodeForOuterBinder.Kind = SyntaxKind.PropertyBlock Then
nodeForOuterBinder = nodeForOuterBinder.Parent
End If
Case SyntaxKind.EventStatement
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing AndAlso nodeForOuterBinder.Kind = SyntaxKind.EventStatement Then
nodeForOuterBinder = nodeForOuterBinder.Parent
End If
Case SyntaxKind.FieldDeclaration,
SyntaxKind.EnumMemberDeclaration
nodeForOuterBinder = parent.Parent
Case SyntaxKind.AttributeList
nodeForOuterBinder = parent.Parent
If nodeForOuterBinder IsNot Nothing Then
parent = nodeForOuterBinder
nodeForOuterBinder = Nothing
GoTo lAgain
End If
End Select
If nodeForOuterBinder Is Nothing Then
Return GetBinderAtOrAbove(parent, parent.SpanStart)
End If
Dim containingBinder As Binder = GetBinderAtOrAbove(nodeForOuterBinder, parent.SpanStart)
Dim symbol As Symbol = Nothing
Select Case parent.Kind
Case SyntaxKind.ClassStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.StructureStatement
symbol = containingBinder.ContainingNamespaceOrType
Case SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.PropertyStatement,
SyntaxKind.EventStatement
If containingBinder.ContainingType IsNot Nothing Then
symbol = SourceMethodSymbol.FindSymbolFromSyntax(
DirectCast(parent, MethodBaseSyntax), _tree, containingBinder.ContainingType)
End If
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
If containingBinder.ContainingType IsNot Nothing Then
symbol = SourceMethodSymbol.FindSymbolFromSyntax(
DirectCast(parent, MethodBaseSyntax), _tree, containingBinder.ContainingType)
Else
symbol = SourceNamedTypeSymbol.FindSymbolFromSyntax(
DirectCast(parent, DelegateStatementSyntax), containingBinder.ContainingNamespaceOrType, _sourceModule)
End If
Case SyntaxKind.FieldDeclaration,
SyntaxKind.EnumStatement,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.ModuleStatement
' we are not using field, enum, module symbols for params or type params resolution
Case Else
Throw ExceptionUtilities.UnexpectedValue(parent.Kind)
End Select
Return BinderBuilder.CreateBinderForDocumentationComment(containingBinder, symbol, binderType)
End Function
Private Function GetContainingNamedTypeBinderForMemberNode(node As VisualBasicSyntaxNode, containingBinder As Binder) As NamedTypeBinder
Dim containingNamedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If containingNamedTypeBinder IsNot Nothing Then
Return containingNamedTypeBinder
End If
' member declared on top-level or in a namespace is enclosed in an implicit type:
If node IsNot Nothing AndAlso (node.Kind = SyntaxKind.NamespaceBlock OrElse node.Kind = SyntaxKind.CompilationUnit) Then
Return DirectCast(
GetBinderForNodeAndUsage(node, NodeUsage.ImplicitClass,
containingBinder:=containingBinder), NamedTypeBinder)
End If
Return Nothing
End Function
Private Shared Function GetParameterDeclarationContainingType(containingBinder As Binder) As NamedTypeSymbol
' Method declarations are bound using either a NamedTypeBinder or a MethodTypeParametersBinder
Dim namedTypeBinder = TryCast(containingBinder, NamedTypeBinder)
If namedTypeBinder Is Nothing Then
' Must be a MethodTypeParametersBinder unless the member
' containing the parameter is outside of a type (in invalid code).
Dim methodDeclarationBinder = TryCast(containingBinder, MethodTypeParametersBinder)
If methodDeclarationBinder Is Nothing Then
Return Nothing
End If
namedTypeBinder = DirectCast(methodDeclarationBinder.ContainingBinder, NamedTypeBinder)
End If
Return namedTypeBinder.ContainingType
End Function
' Given the name of a child namespace, build up a binder from a containing binder.
Private Function BuildNamespaceBinder(containingBinder As NamespaceBinder, childName As NameSyntax, globalNamespaceAllowed As Boolean) As NamespaceBinder
Dim name As String
Select Case childName.Kind
Case SyntaxKind.GlobalName
If globalNamespaceAllowed Then
Return DirectCast(BinderBuilder.CreateBinderForNamespace(_sourceModule, _tree, _sourceModule.GlobalNamespace), NamespaceBinder)
Else
' Global namespace isn't allowed here. Use a namespace named "Global" as error recovery (see corresponding code in DeclarationTreeBuilder)
name = "Global"
End If
Case SyntaxKind.QualifiedName
Dim dotted = DirectCast(childName, QualifiedNameSyntax)
containingBinder = BuildNamespaceBinder(containingBinder, dotted.Left, globalNamespaceAllowed)
name = dotted.Right.Identifier.ValueText
Case SyntaxKind.IdentifierName
name = DirectCast(childName, IdentifierNameSyntax).Identifier.ValueText
Case Else
Throw ExceptionUtilities.UnexpectedValue(childName.Kind)
End Select
For Each symbol As NamespaceOrTypeSymbol In containingBinder.NamespaceSymbol.GetMembers(name)
Dim nsChild = TryCast(symbol, NamespaceSymbol)
If nsChild IsNot Nothing Then
Return New NamespaceBinder(containingBinder, nsChild)
End If
Next
' Namespace is expected to be found by name in parent binder.
Throw ExceptionUtilities.Unreachable
End Function
' Given the name of a method, and the span of the name, and the containing type binder, get the
' binder for the method. We just search all the method symbols with the given name.
Private Function BuildMethodBinder(containingBinder As NamedTypeBinder,
methodSyntax As MethodBaseSyntax,
forBody As Boolean) As Binder
Dim containingType = containingBinder.ContainingType
Dim symbol = SourceMethodSymbol.FindSymbolFromSyntax(methodSyntax, _tree, containingType)
If (symbol IsNot Nothing) AndAlso
(symbol.Kind = SymbolKind.Method) Then
Dim methodSymbol = DirectCast(symbol, SourceMethodSymbol)
If forBody Then
Return BinderBuilder.CreateBinderForMethodBody(methodSymbol, methodSymbol.Syntax, containingBinder)
Else
Return BinderBuilder.CreateBinderForMethodDeclaration(methodSymbol, containingBinder)
End If
Else
' Not sure if there's a case where we get here. For now, fail. Maybe if a declarations
' is so malformed there isn't a symbol for it?
' This can happen if property has multiple accessors.
' Parser allows multiple accessors, but binder will accept only one of a kind
Return containingBinder
End If
End Function
Private Function BuildInitializerBinder(containingBinder As Binder, fieldOrProperty As Symbol, additionalFieldsOrProperties As ImmutableArray(Of Symbol)) As Binder
Return BinderBuilder.CreateBinderForInitializer(containingBinder, fieldOrProperty, additionalFieldsOrProperties)
End Function
Private Function BuildAttributeBinder(containingBinder As Binder, node As VisualBasicSyntaxNode) As Binder
Debug.Assert(node.Kind = SyntaxKind.Attribute)
If containingBinder IsNot Nothing AndAlso node.Parent IsNot Nothing Then
' Go to attribute block
Dim attributeBlock = node.Parent
' Go to statement that owns the attribute
If attributeBlock.Parent IsNot Nothing Then
Select Case attributeBlock.Parent.Kind
Case SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.EnumStatement
' Attributes on a class, module, structure, interface, or enum are contained within those nodes. However, the members of those
' blocks should not be in scope when evaluating expressions within the attribute. Therefore, remove the named type binder from
' the binder hierarchy.
If TypeOf containingBinder Is NamedTypeBinder Then
containingBinder = containingBinder.ContainingBinder
End If
End Select
End If
End If
Return BinderBuilder.CreateBinderForAttribute(_tree, containingBinder, node)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/TypeBlockHighlighter.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 TypeBlockHighlighter
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)
Dim endBlockStatement = TryCast(node, EndBlockStatementSyntax)
If endBlockStatement IsNot Nothing Then
If Not endBlockStatement.IsKind(SyntaxKind.EndClassStatement,
SyntaxKind.EndInterfaceStatement,
SyntaxKind.EndModuleStatement,
SyntaxKind.EndStructureStatement) Then
Return
End If
End If
Dim typeBlock = node.GetAncestor(Of TypeBlockSyntax)()
If typeBlock Is Nothing Then
Return
End If
With typeBlock
With .BlockStatement
Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword)
highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End))
End With
highlights.Add(.EndBlockStatement.Span)
End With
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 TypeBlockHighlighter
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)
Dim endBlockStatement = TryCast(node, EndBlockStatementSyntax)
If endBlockStatement IsNot Nothing Then
If Not endBlockStatement.IsKind(SyntaxKind.EndClassStatement,
SyntaxKind.EndInterfaceStatement,
SyntaxKind.EndModuleStatement,
SyntaxKind.EndStructureStatement) Then
Return
End If
End If
Dim typeBlock = node.GetAncestor(Of TypeBlockSyntax)()
If typeBlock Is Nothing Then
Return
End If
With typeBlock
With .BlockStatement
Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword)
highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End))
End With
highlights.Add(.EndBlockStatement.Span)
End With
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.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.UseCompoundAssignment
{
internal abstract class AbstractUseCompoundAssignmentCodeFixProvider<
TSyntaxKind, TAssignmentSyntax, TExpressionSyntax>
: SyntaxEditorBasedCodeFixProvider
where TSyntaxKind : struct
where TAssignmentSyntax : SyntaxNode
where TExpressionSyntax : SyntaxNode
{
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(IDEDiagnosticIds.UseCompoundAssignmentDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
// See comments in the analyzer for what these maps are for.
private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _binaryToAssignmentMap;
private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _assignmentToTokenMap;
protected AbstractUseCompoundAssignmentCodeFixProvider(
ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds)
{
UseCompoundAssignmentUtilities.GenerateMaps(kinds, out _binaryToAssignmentMap, out _assignmentToTokenMap);
}
protected abstract SyntaxToken Token(TSyntaxKind kind);
protected abstract TAssignmentSyntax Assignment(
TSyntaxKind assignmentOpKind, TExpressionSyntax left, SyntaxToken syntaxToken, TExpressionSyntax right);
protected abstract TExpressionSyntax Increment(TExpressionSyntax left, bool postfix);
protected abstract TExpressionSyntax Decrement(TExpressionSyntax left, bool postfix);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var diagnostic = context.Diagnostics[0];
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(document, diagnostic, c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var syntaxKinds = syntaxFacts.SyntaxKinds;
foreach (var diagnostic in diagnostics)
{
var assignment = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken);
editor.ReplaceNode(assignment,
(current, generator) =>
{
if (current is not TAssignmentSyntax currentAssignment)
return current;
syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(currentAssignment,
out var leftOfAssign, out var equalsToken, out var rightOfAssign);
while (syntaxFacts.IsParenthesizedExpression(rightOfAssign))
rightOfAssign = syntaxFacts.Unparenthesize(rightOfAssign);
syntaxFacts.GetPartsOfBinaryExpression(rightOfAssign,
out _, out var opToken, out var rightExpr);
if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Increment))
return Increment((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment);
if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Decrement))
return Decrement((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment);
var assignmentOpKind = _binaryToAssignmentMap[syntaxKinds.Convert<TSyntaxKind>(rightOfAssign.RawKind)];
var compoundOperator = Token(_assignmentToTokenMap[assignmentOpKind]);
return Assignment(
assignmentOpKind,
(TExpressionSyntax)leftOfAssign,
compoundOperator.WithTriviaFrom(equalsToken),
(TExpressionSyntax)rightExpr);
});
}
return Task.CompletedTask;
}
protected virtual bool PreferPostfix(ISyntaxFactsService syntaxFacts, TAssignmentSyntax currentAssignment)
{
// If we have `x = x + 1;` on it's own, then we prefer `x++` as idiomatic.
if (syntaxFacts.IsSimpleAssignmentStatement(currentAssignment.Parent))
return true;
// In any other circumstance, the value of the assignment might be read, so we need to transform to
// ++x to ensure that we preserve semantics.
return false;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.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.UseCompoundAssignment
{
internal abstract class AbstractUseCompoundAssignmentCodeFixProvider<
TSyntaxKind, TAssignmentSyntax, TExpressionSyntax>
: SyntaxEditorBasedCodeFixProvider
where TSyntaxKind : struct
where TAssignmentSyntax : SyntaxNode
where TExpressionSyntax : SyntaxNode
{
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(IDEDiagnosticIds.UseCompoundAssignmentDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
// See comments in the analyzer for what these maps are for.
private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _binaryToAssignmentMap;
private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _assignmentToTokenMap;
protected AbstractUseCompoundAssignmentCodeFixProvider(
ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds)
{
UseCompoundAssignmentUtilities.GenerateMaps(kinds, out _binaryToAssignmentMap, out _assignmentToTokenMap);
}
protected abstract SyntaxToken Token(TSyntaxKind kind);
protected abstract TAssignmentSyntax Assignment(
TSyntaxKind assignmentOpKind, TExpressionSyntax left, SyntaxToken syntaxToken, TExpressionSyntax right);
protected abstract TExpressionSyntax Increment(TExpressionSyntax left, bool postfix);
protected abstract TExpressionSyntax Decrement(TExpressionSyntax left, bool postfix);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var diagnostic = context.Diagnostics[0];
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(document, diagnostic, c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var syntaxKinds = syntaxFacts.SyntaxKinds;
foreach (var diagnostic in diagnostics)
{
var assignment = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken);
editor.ReplaceNode(assignment,
(current, generator) =>
{
if (current is not TAssignmentSyntax currentAssignment)
return current;
syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(currentAssignment,
out var leftOfAssign, out var equalsToken, out var rightOfAssign);
while (syntaxFacts.IsParenthesizedExpression(rightOfAssign))
rightOfAssign = syntaxFacts.Unparenthesize(rightOfAssign);
syntaxFacts.GetPartsOfBinaryExpression(rightOfAssign,
out _, out var opToken, out var rightExpr);
if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Increment))
return Increment((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment);
if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Decrement))
return Decrement((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment);
var assignmentOpKind = _binaryToAssignmentMap[syntaxKinds.Convert<TSyntaxKind>(rightOfAssign.RawKind)];
var compoundOperator = Token(_assignmentToTokenMap[assignmentOpKind]);
return Assignment(
assignmentOpKind,
(TExpressionSyntax)leftOfAssign,
compoundOperator.WithTriviaFrom(equalsToken),
(TExpressionSyntax)rightExpr);
});
}
return Task.CompletedTask;
}
protected virtual bool PreferPostfix(ISyntaxFactsService syntaxFacts, TAssignmentSyntax currentAssignment)
{
// If we have `x = x + 1;` on it's own, then we prefer `x++` as idiomatic.
if (syntaxFacts.IsSimpleAssignmentStatement(currentAssignment.Parent))
return true;
// In any other circumstance, the value of the assignment might be read, so we need to transform to
// ++x to ensure that we preserve semantics.
return false;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/Core/CodeAnalysisTest/Collections/SmallDictionaryTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class SmallDictionaryTests
{
[Fact]
public void SmallDictionaryAlwaysBalanced()
{
var sd = new SmallDictionary<int, string>();
sd.Add(1, "1");
sd.AssertBalanced();
sd.Add(10, "1");
sd.AssertBalanced();
sd.Add(2, "1");
sd.AssertBalanced();
sd.Add(1000, "1");
sd.AssertBalanced();
sd.Add(-123, "1");
sd.AssertBalanced();
sd.Add(0, "1");
sd.AssertBalanced();
sd.Add(4, "1");
sd.AssertBalanced();
sd.Add(5, "1");
sd.AssertBalanced();
sd.Add(6, "1");
sd.AssertBalanced();
}
[Fact]
public void TestSmallDict()
{
var ht = new SmallDictionary<int, int>();
const int elements = 150;
for (int i = 0; i < elements; i += 10)
{
ht.Add(i, i);
ht.AssertBalanced();
ht.Add(i - 2, i - 2);
ht.AssertBalanced();
ht.Add(i - 3, i - 3);
ht.AssertBalanced();
ht.Add(i - 4, i - 4);
ht.AssertBalanced();
ht.Add(i - 6, i - 6);
ht.AssertBalanced();
ht.Add(i - 5, i - 5);
ht.AssertBalanced();
ht.Add(i - 1, i - 1);
ht.AssertBalanced();
ht.Add(i - 7, i - 7);
ht.AssertBalanced();
ht.Add(i - 8, i - 8);
ht.AssertBalanced();
ht.Add(i - 9, i - 9);
ht.AssertBalanced();
}
Assert.Equal(150, ht.Count());
for (int i = 0; i < elements; i += 10)
{
Assert.Equal(ht[i], i);
Assert.Equal(ht[i - 2], i - 2);
Assert.Equal(ht[i - 3], i - 3);
Assert.Equal(ht[i - 4], i - 4);
Assert.Equal(ht[i - 6], i - 6);
Assert.Equal(ht[i - 5], i - 5);
Assert.Equal(ht[i - 1], i - 1);
Assert.Equal(ht[i - 7], i - 7);
Assert.Equal(ht[i - 8], i - 8);
Assert.Equal(ht[i - 9], i - 9);
}
foreach (var p in ht)
{
Assert.Equal(p.Key, p.Value);
}
var keys = ht.Keys.ToArray();
var values = ht.Values.ToArray();
for (int i = 0, l = ht.Count(); i < l; i++)
{
Assert.Equal(keys[i], values[i]);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class SmallDictionaryTests
{
[Fact]
public void SmallDictionaryAlwaysBalanced()
{
var sd = new SmallDictionary<int, string>();
sd.Add(1, "1");
sd.AssertBalanced();
sd.Add(10, "1");
sd.AssertBalanced();
sd.Add(2, "1");
sd.AssertBalanced();
sd.Add(1000, "1");
sd.AssertBalanced();
sd.Add(-123, "1");
sd.AssertBalanced();
sd.Add(0, "1");
sd.AssertBalanced();
sd.Add(4, "1");
sd.AssertBalanced();
sd.Add(5, "1");
sd.AssertBalanced();
sd.Add(6, "1");
sd.AssertBalanced();
}
[Fact]
public void TestSmallDict()
{
var ht = new SmallDictionary<int, int>();
const int elements = 150;
for (int i = 0; i < elements; i += 10)
{
ht.Add(i, i);
ht.AssertBalanced();
ht.Add(i - 2, i - 2);
ht.AssertBalanced();
ht.Add(i - 3, i - 3);
ht.AssertBalanced();
ht.Add(i - 4, i - 4);
ht.AssertBalanced();
ht.Add(i - 6, i - 6);
ht.AssertBalanced();
ht.Add(i - 5, i - 5);
ht.AssertBalanced();
ht.Add(i - 1, i - 1);
ht.AssertBalanced();
ht.Add(i - 7, i - 7);
ht.AssertBalanced();
ht.Add(i - 8, i - 8);
ht.AssertBalanced();
ht.Add(i - 9, i - 9);
ht.AssertBalanced();
}
Assert.Equal(150, ht.Count());
for (int i = 0; i < elements; i += 10)
{
Assert.Equal(ht[i], i);
Assert.Equal(ht[i - 2], i - 2);
Assert.Equal(ht[i - 3], i - 3);
Assert.Equal(ht[i - 4], i - 4);
Assert.Equal(ht[i - 6], i - 6);
Assert.Equal(ht[i - 5], i - 5);
Assert.Equal(ht[i - 1], i - 1);
Assert.Equal(ht[i - 7], i - 7);
Assert.Equal(ht[i - 8], i - 8);
Assert.Equal(ht[i - 9], i - 9);
}
foreach (var p in ht)
{
Assert.Equal(p.Key, p.Value);
}
var keys = ht.Keys.ToArray();
var values = ht.Values.ToArray();
for (int i = 0, l = ht.Count(); i < l; i++)
{
Assert.Equal(keys[i], values[i]);
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/CSharp/Test/Semantic/Semantics/ScriptTestFixtures.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities
{
public static class ScriptTestFixtures
{
internal static MetadataReference HostRef = MetadataReference.CreateFromAssemblyInternal(typeof(ScriptTestFixtures).GetTypeInfo().Assembly);
public class B
{
public int x = 1, w = 4;
}
public class C : B, I
{
public static readonly int StaticField = 123;
public int Y => 2;
public string N { get; set; } = "2";
public int Z() => 3;
public override int GetHashCode() => 123;
}
public interface I
{
string N { get; set; }
int Z();
}
private class PrivateClass : I
{
public string N { get; set; } = null;
public int Z() => 3;
}
public class B2
{
public int x = 1, w = 4;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities
{
public static class ScriptTestFixtures
{
internal static MetadataReference HostRef = MetadataReference.CreateFromAssemblyInternal(typeof(ScriptTestFixtures).GetTypeInfo().Assembly);
public class B
{
public int x = 1, w = 4;
}
public class C : B, I
{
public static readonly int StaticField = 123;
public int Y => 2;
public string N { get; set; } = "2";
public int Z() => 3;
public override int GetHashCode() => 123;
}
public interface I
{
string N { get; set; }
int Z();
}
private class PrivateClass : I
{
public string N { get; set; } = null;
public int Z() => 3;
}
public class B2
{
public int x = 1, w = 4;
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Compilers/CSharp/Portable/FlowAnalysis/VariablesDeclaredWalker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A region analysis walker that records declared variables.
/// </summary>
internal class VariablesDeclaredWalker : AbstractRegionControlFlowPass
{
internal static IEnumerable<Symbol> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
{
var walker = new VariablesDeclaredWalker(compilation, member, node, firstInRegion, lastInRegion);
try
{
bool badRegion = false;
walker.Analyze(ref badRegion);
return badRegion ? SpecializedCollections.EmptyEnumerable<Symbol>() : walker._variablesDeclared;
}
finally
{
walker.Free();
}
}
private HashSet<Symbol> _variablesDeclared = new HashSet<Symbol>();
internal VariablesDeclaredWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
: base(compilation, member, node, firstInRegion, lastInRegion)
{
}
protected override void Free()
{
base.Free();
_variablesDeclared = null;
}
public override void VisitPattern(BoundPattern pattern)
{
base.VisitPattern(pattern);
NoteDeclaredPatternVariables(pattern);
}
protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection)
{
foreach (var label in node.SwitchLabels)
{
NoteDeclaredPatternVariables(label.Pattern);
}
base.VisitSwitchSection(node, isLastSection);
}
/// <summary>
/// Record declared variables in the pattern.
/// </summary>
private void NoteDeclaredPatternVariables(BoundPattern pattern)
{
if (IsInside)
{
switch (pattern)
{
case BoundDeclarationPattern decl:
{
// The variable may be null if it is a discard designation `_`.
if (decl.Variable?.Kind == SymbolKind.Local)
{
// Because this API only returns local symbols and parameters,
// we exclude pattern variables that have become fields in scripts.
_variablesDeclared.Add(decl.Variable);
}
}
break;
case BoundRecursivePattern recur:
{
if (recur.Variable?.Kind == SymbolKind.Local)
{
_variablesDeclared.Add(recur.Variable);
}
}
break;
}
}
}
public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node)
{
if (IsInside)
{
_variablesDeclared.Add(node.LocalSymbol);
}
return base.VisitLocalDeclaration(node);
}
public override BoundNode VisitLambda(BoundLambda node)
{
if (IsInside && !node.WasCompilerGenerated)
{
foreach (var parameter in node.Symbol.Parameters)
{
_variablesDeclared.Add(parameter);
}
}
return base.VisitLambda(node);
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
if (IsInside && !node.WasCompilerGenerated)
{
foreach (var parameter in node.Symbol.Parameters)
{
_variablesDeclared.Add(parameter);
}
}
return base.VisitLocalFunctionStatement(node);
}
public override void VisitForEachIterationVariables(BoundForEachStatement node)
{
if (IsInside)
{
var deconstructionAssignment = node.DeconstructionOpt?.DeconstructionAssignment;
if (deconstructionAssignment == null)
{
_variablesDeclared.AddAll(node.IterationVariables);
}
else
{
// Deconstruction foreach declares multiple variables.
((BoundTupleExpression)deconstructionAssignment.Left).VisitAllElements((x, self) => self.Visit(x), this);
}
}
}
protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState)
{
if (IsInside)
{
var local = catchBlock.Locals.FirstOrDefault();
if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable)
{
_variablesDeclared.Add(local);
}
}
base.VisitCatchBlock(catchBlock, ref finallyState);
}
public override BoundNode VisitQueryClause(BoundQueryClause node)
{
if (IsInside)
{
if ((object)node.DefinedSymbol != null)
{
_variablesDeclared.Add(node.DefinedSymbol);
}
}
return base.VisitQueryClause(node);
}
protected override void VisitLvalue(BoundLocal node)
{
VisitLocal(node);
}
public override BoundNode VisitLocal(BoundLocal node)
{
if (IsInside && node.DeclarationKind != BoundLocalDeclarationKind.None)
{
_variablesDeclared.Add(node.LocalSymbol);
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A region analysis walker that records declared variables.
/// </summary>
internal class VariablesDeclaredWalker : AbstractRegionControlFlowPass
{
internal static IEnumerable<Symbol> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
{
var walker = new VariablesDeclaredWalker(compilation, member, node, firstInRegion, lastInRegion);
try
{
bool badRegion = false;
walker.Analyze(ref badRegion);
return badRegion ? SpecializedCollections.EmptyEnumerable<Symbol>() : walker._variablesDeclared;
}
finally
{
walker.Free();
}
}
private HashSet<Symbol> _variablesDeclared = new HashSet<Symbol>();
internal VariablesDeclaredWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
: base(compilation, member, node, firstInRegion, lastInRegion)
{
}
protected override void Free()
{
base.Free();
_variablesDeclared = null;
}
public override void VisitPattern(BoundPattern pattern)
{
base.VisitPattern(pattern);
NoteDeclaredPatternVariables(pattern);
}
protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection)
{
foreach (var label in node.SwitchLabels)
{
NoteDeclaredPatternVariables(label.Pattern);
}
base.VisitSwitchSection(node, isLastSection);
}
/// <summary>
/// Record declared variables in the pattern.
/// </summary>
private void NoteDeclaredPatternVariables(BoundPattern pattern)
{
if (IsInside)
{
switch (pattern)
{
case BoundDeclarationPattern decl:
{
// The variable may be null if it is a discard designation `_`.
if (decl.Variable?.Kind == SymbolKind.Local)
{
// Because this API only returns local symbols and parameters,
// we exclude pattern variables that have become fields in scripts.
_variablesDeclared.Add(decl.Variable);
}
}
break;
case BoundRecursivePattern recur:
{
if (recur.Variable?.Kind == SymbolKind.Local)
{
_variablesDeclared.Add(recur.Variable);
}
}
break;
}
}
}
public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node)
{
if (IsInside)
{
_variablesDeclared.Add(node.LocalSymbol);
}
return base.VisitLocalDeclaration(node);
}
public override BoundNode VisitLambda(BoundLambda node)
{
if (IsInside && !node.WasCompilerGenerated)
{
foreach (var parameter in node.Symbol.Parameters)
{
_variablesDeclared.Add(parameter);
}
}
return base.VisitLambda(node);
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
if (IsInside && !node.WasCompilerGenerated)
{
foreach (var parameter in node.Symbol.Parameters)
{
_variablesDeclared.Add(parameter);
}
}
return base.VisitLocalFunctionStatement(node);
}
public override void VisitForEachIterationVariables(BoundForEachStatement node)
{
if (IsInside)
{
var deconstructionAssignment = node.DeconstructionOpt?.DeconstructionAssignment;
if (deconstructionAssignment == null)
{
_variablesDeclared.AddAll(node.IterationVariables);
}
else
{
// Deconstruction foreach declares multiple variables.
((BoundTupleExpression)deconstructionAssignment.Left).VisitAllElements((x, self) => self.Visit(x), this);
}
}
}
protected override void VisitCatchBlock(BoundCatchBlock catchBlock, ref LocalState finallyState)
{
if (IsInside)
{
var local = catchBlock.Locals.FirstOrDefault();
if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable)
{
_variablesDeclared.Add(local);
}
}
base.VisitCatchBlock(catchBlock, ref finallyState);
}
public override BoundNode VisitQueryClause(BoundQueryClause node)
{
if (IsInside)
{
if ((object)node.DefinedSymbol != null)
{
_variablesDeclared.Add(node.DefinedSymbol);
}
}
return base.VisitQueryClause(node);
}
protected override void VisitLvalue(BoundLocal node)
{
VisitLocal(node);
}
public override BoundNode VisitLocal(BoundLocal node)
{
if (IsInside && node.DeclarationKind != BoundLocalDeclarationKind.None)
{
_variablesDeclared.Add(node.LocalSymbol);
}
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Features/Core/Portable/EditAndContinue/Remote/ActiveStatementSpanProviderCallback.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class ActiveStatementSpanProviderCallback
{
private readonly ActiveStatementSpanProvider _provider;
public ActiveStatementSpanProviderCallback(ActiveStatementSpanProvider provider)
=> _provider = provider;
/// <summary>
/// Remote API.
/// </summary>
public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(DocumentId? documentId, string filePath, CancellationToken cancellationToken)
{
try
{
return await _provider(documentId, filePath, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ImmutableArray<ActiveStatementSpan>.Empty;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class ActiveStatementSpanProviderCallback
{
private readonly ActiveStatementSpanProvider _provider;
public ActiveStatementSpanProviderCallback(ActiveStatementSpanProvider provider)
=> _provider = provider;
/// <summary>
/// Remote API.
/// </summary>
public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(DocumentId? documentId, string filePath, CancellationToken cancellationToken)
{
try
{
return await _provider(documentId, filePath, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ImmutableArray<ActiveStatementSpan>.Empty;
}
}
}
}
| -1 |
dotnet/roslyn | 55,980 | Handle XamlDefinition with line and column | When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | LinglingTong | "2021-08-27T23:03:17Z" | "2021-08-30T15:31:45Z" | 94dfadf3e5280cb66b5bf7d11723f91a64c7d4d3 | 59220cc88f6549c0a81c895e39ad0a798095d5f5 | Handle XamlDefinition with line and column. When XAML GoToDefinitionHandler gets a XamlSourceDefinition, if the line and column values are available, we will use those values to build up the LSP location directly instead of converting them to text span first. This will help our go to definition on event handler scenarios work correctly and also save some exact work.
I also sneaked in a couple XamlCapabilities changes as well:
- Removed "\n" trigger character for OnTypeFormatting as we handle OnEnter formatting in smart indent.
- Removed ">" trigger character for AutoInsert as we are going to let ">" trigger OnTypeFormatting and Auto-insert end tag over there. | ./src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.MoveDeclarationNearReference;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.ReplaceDiscardDeclarationsWithAssignments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues
{
/// <summary>
/// Code fixer for unused expression value diagnostics reported by <see cref="AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer"/>.
/// We provide following code fixes:
/// 1. If the unused value assigned to a local/parameter has no side-effects,
/// we recommend removing the assignment. We consider an expression value to have no side effects
/// if one of the following is true:
/// 1. Value is a compile time constant.
/// 2. Value is a local or parameter reference.
/// 3. Value is a field reference with no or implicit this instance.
/// 2. Otherwise, if user preference is set to DiscardVariable, and project's
/// language version supports discard variable, we recommend assigning the value to discard.
/// 3. Otherwise, we recommend assigning the value to a new unused local variable which has no reads.
/// </summary>
internal abstract class AbstractRemoveUnusedValuesCodeFixProvider<TExpressionSyntax, TStatementSyntax, TBlockSyntax,
TExpressionStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax, TForEachStatementSyntax,
TSwitchCaseBlockSyntax, TSwitchCaseLabelOrClauseSyntax, TCatchStatementSyntax, TCatchBlockSyntax>
: SyntaxEditorBasedCodeFixProvider
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TBlockSyntax : TStatementSyntax
where TExpressionStatementSyntax : TStatementSyntax
where TLocalDeclarationStatementSyntax : TStatementSyntax
where TForEachStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
where TSwitchCaseBlockSyntax : SyntaxNode
where TSwitchCaseLabelOrClauseSyntax : SyntaxNode
{
private static readonly SyntaxAnnotation s_memberAnnotation = new();
private static readonly SyntaxAnnotation s_newLocalDeclarationStatementAnnotation = new();
private static readonly SyntaxAnnotation s_unusedLocalDeclarationAnnotation = new();
private static readonly SyntaxAnnotation s_existingLocalDeclarationWithoutInitializerAnnotation = new();
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.ExpressionValueIsUnusedDiagnosticId,
IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;
/// <summary>
/// Method to update the identifier token for the local/parameter declaration or reference
/// that was flagged as an unused value write by the analyzer.
/// Returns null if the provided node is not one of the handled node kinds.
/// Otherwise, returns the new node with updated identifier.
/// </summary>
/// <param name="node">Flaggged node containing the identifier token to be replaced.</param>
/// <param name="newName">New identifier token</param>
protected abstract SyntaxNode TryUpdateNameForFlaggedNode(SyntaxNode node, SyntaxToken newName);
/// <summary>
/// Gets the identifier token for the iteration variable of the given foreach statement node.
/// </summary>
protected abstract SyntaxToken GetForEachStatementIdentifier(TForEachStatementSyntax node);
/// <summary>
/// Wraps the given statements within a block statement.
/// Note this method is invoked when replacing a statement that is parented by a non-block statement syntax.
/// </summary>
protected abstract TBlockSyntax WrapWithBlockIfNecessary(IEnumerable<TStatementSyntax> statements);
/// <summary>
/// Inserts the given declaration statement at the start of the given switch case block.
/// </summary>
protected abstract void InsertAtStartOfSwitchCaseBlockForDeclarationInCaseLabelOrClause(TSwitchCaseBlockSyntax switchCaseBlock, SyntaxEditor editor, TLocalDeclarationStatementSyntax declarationStatement);
/// <summary>
/// Gets the replacement node for a compound assignment expression whose
/// assigned value is redundant.
/// For example, "x += MethodCall()", where assignment to 'x' is redundant
/// is replaced with "_ = MethodCall()" or "var unused = MethodCall()"
/// </summary>
protected abstract SyntaxNode GetReplacementNodeForCompoundAssignment(
SyntaxNode originalCompoundAssignment,
SyntaxNode newAssignmentTarget,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts);
/// <summary>
/// Rewrite the parent of a node which was rewritted by <see cref="TryUpdateNameForFlaggedNode"/>.
/// </summary>
/// <param name="parent">The original parent of the node rewritten by <see cref="TryUpdateNameForFlaggedNode"/>.</param>
/// <param name="newNameNode">The rewritten node produced by <see cref="TryUpdateNameForFlaggedNode"/>.</param>
/// <param name="editor">The syntax editor for the code fix.</param>
/// <param name="syntaxFacts">The syntax facts for the current language.</param>
/// <returns>The replacement node to use in the rewritten syntax tree; otherwise, <see langword="null"/> to only
/// rewrite the node originally rewritten by <see cref="TryUpdateNameForFlaggedNode"/>.</returns>
protected virtual SyntaxNode TryUpdateParentOfUpdatedNode(SyntaxNode parent, SyntaxNode newNameNode, SyntaxEditor editor, ISyntaxFacts syntaxFacts)
{
return null;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics[0];
if (!AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var preference))
{
return;
}
var isRemovableAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic);
string title;
if (isRemovableAssignment)
{
// Recommend removing the redundant constant value assignment.
title = CodeFixesResources.Remove_redundant_assignment;
}
else
{
// Recommend using discard/unused local for redundant non-constant assignment.
switch (preference)
{
case UnusedValuePreference.DiscardVariable:
if (IsForEachIterationVariableDiagnostic(diagnostic, context.Document, context.CancellationToken))
{
// Do not offer a fix to replace unused foreach iteration variable with discard.
// User should probably replace it with a for loop based on the collection length.
return;
}
title = CodeFixesResources.Use_discard_underscore;
// Check if this is compound assignment which is not parented by an expression statement,
// for example "return x += M();" OR "=> x ??= new C();"
// If so, we will be replacing this compound assignment with the underlying binary operation.
// For the above examples, it will be "return x + M();" AND "=> x ?? new C();" respectively.
// For these cases, we want to show the title as "Remove redundant assignment" instead of "Use discard _".
var syntaxFacts = context.Document.GetLanguageService<ISyntaxFactsService>();
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span, getInnermostNodeForTie: true);
if (syntaxFacts.IsLeftSideOfCompoundAssignment(node) &&
!syntaxFacts.IsExpressionStatement(node.Parent))
{
title = CodeFixesResources.Remove_redundant_assignment;
}
break;
case UnusedValuePreference.UnusedLocalVariable:
title = CodeFixesResources.Use_discarded_local;
break;
default:
return;
}
}
context.RegisterCodeFix(
new MyCodeAction(
title,
c => FixAsync(context.Document, diagnostic, c),
equivalenceKey: GetEquivalenceKey(preference, isRemovableAssignment)),
diagnostic);
return;
}
private static bool IsForEachIterationVariableDiagnostic(Diagnostic diagnostic, Document document, CancellationToken cancellationToken)
{
// Do not offer a fix to replace unused foreach iteration variable with discard.
// User should probably replace it with a for loop based on the collection length.
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
return syntaxFacts.IsForEachStatement(diagnostic.Location.FindNode(cancellationToken));
}
private static string GetEquivalenceKey(UnusedValuePreference preference, bool isRemovableAssignment)
=> preference.ToString() + isRemovableAssignment;
private static string GetEquivalenceKey(Diagnostic diagnostic)
{
if (!AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var preference))
{
return string.Empty;
}
var isRemovableAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic);
return GetEquivalenceKey(preference, isRemovableAssignment);
}
/// <summary>
/// Flag to indicate if the code fix can introduce local declaration statements
/// that need to be moved closer to the first reference of the declared variable.
/// This is currently only possible for the unused value assignment fix.
/// </summary>
private static bool NeedsToMoveNewLocalDeclarationsNearReference(string diagnosticId)
=> diagnosticId == IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string equivalenceKey, CancellationToken cancellationToken)
{
return equivalenceKey == GetEquivalenceKey(diagnostic) &&
!IsForEachIterationVariableDiagnostic(diagnostic, document, cancellationToken);
}
private static IEnumerable<IGrouping<SyntaxNode, Diagnostic>> GetDiagnosticsGroupedByMember(
ImmutableArray<Diagnostic> diagnostics,
ISyntaxFactsService syntaxFacts,
SyntaxNode root,
out string diagnosticId,
out UnusedValuePreference preference,
out bool removeAssignments)
{
diagnosticId = diagnostics[0].Id;
var success = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostics[0], out preference);
Debug.Assert(success);
removeAssignments = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostics[0]);
#if DEBUG
foreach (var diagnostic in diagnostics)
{
Debug.Assert(diagnosticId == diagnostic.Id);
Debug.Assert(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var diagnosticPreference) &&
diagnosticPreference == preference);
Debug.Assert(removeAssignments == AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic));
}
#endif
return GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root);
}
private static IEnumerable<IGrouping<SyntaxNode, Diagnostic>> GetDiagnosticsGroupedByMember(
ImmutableArray<Diagnostic> diagnostics,
ISyntaxFactsService syntaxFacts,
SyntaxNode root)
=> diagnostics.GroupBy(d => syntaxFacts.GetContainingMemberDeclaration(root, d.Location.SourceSpan.Start));
private static async Task<Document> PreprocessDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
// Track all the member declaration nodes that have diagnostics.
// We will post process all these tracked nodes after applying the fix (see "PostProcessDocumentAsync" below in this source file).
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var memberDeclarations = GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root).Select(g => g.Key);
root = root.ReplaceNodes(memberDeclarations, computeReplacementNode: (_, n) => n.WithAdditionalAnnotations(s_memberAnnotation));
return document.WithSyntaxRoot(root);
}
protected sealed override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
document = await PreprocessDocumentAsync(document, diagnostics, cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var originalEditor = editor;
editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
try
{
// We compute the code fix in two passes:
// 1. The first pass groups the diagnostics to fix by containing member declaration and
// computes and applies the core code fixes. Grouping is done to ensure we choose
// the most appropriate name for new unused local declarations, which can clash
// with existing local declarations in the method body.
// 2. Second pass (PostProcessDocumentAsync) performs additional syntax manipulations
// for the fixes produced from from first pass:
// a. Replace discard declarations, such as "var _ = M();" that conflict with newly added
// discard assignments, with discard assignments of the form "_ = M();"
// b. Move newly introduced local declaration statements closer to the local variable's
// first reference.
// Get diagnostics grouped by member.
var diagnosticsGroupedByMember = GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root,
out var diagnosticId, out var preference, out var removeAssignments);
// First pass to compute and apply the core code fixes.
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnosticsToFix in diagnosticsGroupedByMember)
{
var containingMemberDeclaration = diagnosticsToFix.Key;
using var nameGenerator = new UniqueVariableNameGenerator(containingMemberDeclaration, semanticModel, semanticFacts, cancellationToken);
await FixAllAsync(diagnosticId, diagnosticsToFix.Select(d => d), document, semanticModel, root, containingMemberDeclaration, preference,
removeAssignments, nameGenerator, editor, syntaxFacts, cancellationToken).ConfigureAwait(false);
}
// Second pass to post process the document.
var currentRoot = editor.GetChangedRoot();
var newRoot = await PostProcessDocumentAsync(document, currentRoot,
diagnosticId, preference, cancellationToken).ConfigureAwait(false);
if (currentRoot != newRoot)
{
editor.ReplaceNode(root, newRoot);
}
}
finally
{
originalEditor.ReplaceNode(originalEditor.OriginalRoot, editor.GetChangedRoot());
}
}
private async Task FixAllAsync(
string diagnosticId,
IEnumerable<Diagnostic> diagnostics,
Document document,
SemanticModel semanticModel,
SyntaxNode root,
SyntaxNode containingMemberDeclaration,
UnusedValuePreference preference,
bool removeAssignments,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
switch (diagnosticId)
{
case IDEDiagnosticIds.ExpressionValueIsUnusedDiagnosticId:
// Make sure the inner diagnostics are placed first
FixAllExpressionValueIsUnusedDiagnostics(diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start), semanticModel, root,
preference, nameGenerator, editor, syntaxFacts);
break;
case IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId:
// Make sure the diagnostics are placed in order.
// Example:
// int a = 0; int b = 1;
// After fix it would be int a; int b;
await FixAllValueAssignedIsUnusedDiagnosticsAsync(diagnostics.OrderBy(d => d.Location.SourceSpan.Start), document, semanticModel, root, containingMemberDeclaration,
preference, removeAssignments, nameGenerator, editor, syntaxFacts, cancellationToken).ConfigureAwait(false);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private static void FixAllExpressionValueIsUnusedDiagnostics(
IOrderedEnumerable<Diagnostic> diagnostics,
SemanticModel semanticModel,
SyntaxNode root,
UnusedValuePreference preference,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts)
{
// This method applies the code fix for diagnostics reported for expression statement dropping values.
// We replace each flagged expression statement with an assignment to a discard variable or a new unused local,
// based on the user's preference.
// Note: The diagnostic order here should be inner first and outer second.
// Example: Foo1(() => { Foo2(); })
// Foo2() should be the first in this case.
foreach (var diagnostic in diagnostics)
{
var expressionStatement = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<TExpressionStatementSyntax>();
if (expressionStatement == null)
{
continue;
}
switch (preference)
{
case UnusedValuePreference.DiscardVariable:
Debug.Assert(semanticModel.Language != LanguageNames.VisualBasic);
var expression = syntaxFacts.GetExpressionOfExpressionStatement(expressionStatement);
editor.ReplaceNode(expression, (node, generator) =>
{
var discardAssignmentExpression = (TExpressionSyntax)generator.AssignmentStatement(
left: generator.IdentifierName(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName),
right: node.WithoutTrivia())
.WithTriviaFrom(node)
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
return discardAssignmentExpression;
});
break;
case UnusedValuePreference.UnusedLocalVariable:
var name = nameGenerator.GenerateUniqueNameAtSpanStart(expressionStatement).ValueText;
editor.ReplaceNode(expressionStatement, (node, generator) =>
{
var expression = syntaxFacts.GetExpressionOfExpressionStatement(node);
// Add Simplifier annotation so that 'var'/explicit type is correctly added based on user options.
var localDecl = editor.Generator.LocalDeclarationStatement(
name: name,
initializer: expression.WithoutLeadingTrivia())
.WithTriviaFrom(node)
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
return localDecl;
});
break;
}
}
}
private async Task FixAllValueAssignedIsUnusedDiagnosticsAsync(
IOrderedEnumerable<Diagnostic> diagnostics,
Document document,
SemanticModel semanticModel,
SyntaxNode root,
SyntaxNode containingMemberDeclaration,
UnusedValuePreference preference,
bool removeAssignments,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
// This method applies the code fix for diagnostics reported for unused value assignments to local/parameter.
// The actual code fix depends on whether or not the right hand side of the assignment has side effects.
// For example, if the right hand side is a constant or a reference to a local/parameter, then it has no side effects.
// The lack of side effects is indicated by the "removeAssignments" parameter for this function.
// If the right hand side has no side effects, then we can replace the assignments with variable declarations that have no initializer
// or completely remove the statement.
// If the right hand side does have side effects, we replace the identifier token for unused value assignment with
// a new identifier token (either discard '_' or new unused local variable name).
// For both the above cases, if the original diagnostic was reported on a local declaration, i.e. redundant initialization
// at declaration, then we also add a new variable declaration statement without initializer for this local.
using var _1 = PooledDictionary<SyntaxNode, SyntaxNode>.GetInstance(out var nodeReplacementMap);
using var _2 = PooledHashSet<SyntaxNode>.GetInstance(out var nodesToRemove);
using var _3 = PooledHashSet<(TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode node)>.GetInstance(out var nodesToAdd);
// Indicates if the node's trivia was processed.
using var _4 = PooledHashSet<SyntaxNode>.GetInstance(out var processedNodes);
using var _5 = PooledHashSet<TLocalDeclarationStatementSyntax>.GetInstance(out var candidateDeclarationStatementsForRemoval);
var hasAnyUnusedLocalAssignment = false;
foreach (var (node, isUnusedLocalAssignment) in GetNodesToFix())
{
hasAnyUnusedLocalAssignment |= isUnusedLocalAssignment;
var declaredLocal = semanticModel.GetDeclaredSymbol(node, cancellationToken) as ILocalSymbol;
if (declaredLocal == null && node.Parent is TCatchStatementSyntax)
{
declaredLocal = semanticModel.GetDeclaredSymbol(node.Parent, cancellationToken) as ILocalSymbol;
}
string newLocalNameOpt = null;
if (removeAssignments)
{
// Removable assignment or initialization, such that right hand side has no side effects.
if (declaredLocal != null)
{
// Redundant initialization.
// For example, "int a = 0;"
var variableDeclarator = node.FirstAncestorOrSelf<TVariableDeclaratorSyntax>();
Debug.Assert(variableDeclarator != null);
nodesToRemove.Add(variableDeclarator);
// Local declaration statement containing the declarator might be a candidate for removal if all its variables get marked for removal.
var candidate = GetCandidateLocalDeclarationForRemoval(variableDeclarator);
if (candidate != null)
{
candidateDeclarationStatementsForRemoval.Add(candidate);
}
}
else
{
// Redundant assignment or increment/decrement.
if (syntaxFacts.IsOperandOfIncrementOrDecrementExpression(node))
{
// For example, C# increment operation "a++;"
Debug.Assert(node.Parent.Parent is TExpressionStatementSyntax);
nodesToRemove.Add(node.Parent.Parent);
}
else
{
Debug.Assert(syntaxFacts.IsLeftSideOfAnyAssignment(node));
if (node.Parent is TStatementSyntax)
{
// For example, VB simple assignment statement "a = 0"
nodesToRemove.Add(node.Parent);
}
else if (node.Parent is TExpressionSyntax && node.Parent.Parent is TExpressionStatementSyntax)
{
// For example, C# simple assignment statement "a = 0;"
nodesToRemove.Add(node.Parent.Parent);
}
else
{
// For example, C# nested assignment statement "a = b = 0;", where assignment to 'b' is redundant.
// We replace the node with "a = 0;"
nodeReplacementMap.Add(node.Parent, syntaxFacts.GetRightHandSideOfAssignment(node.Parent));
}
}
}
}
else
{
// Value initialization/assignment where the right hand side may have side effects,
// and hence needs to be preserved in fixed code.
// For example, "x = MethodCall();" is replaced with "_ = MethodCall();" or "var unused = MethodCall();"
// Replace the flagged variable's indentifier token with new named, based on user's preference.
var newNameToken = preference == UnusedValuePreference.DiscardVariable
? document.GetRequiredLanguageService<SyntaxGeneratorInternal>().Identifier(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName)
: nameGenerator.GenerateUniqueNameAtSpanStart(node);
newLocalNameOpt = newNameToken.ValueText;
var newNameNode = TryUpdateNameForFlaggedNode(node, newNameToken);
if (newNameNode == null)
{
continue;
}
// Is this is compound assignment?
if (syntaxFacts.IsLeftSideOfAnyAssignment(node) && !syntaxFacts.IsLeftSideOfAssignment(node))
{
// Compound assignment is changed to simple assignment.
// For example, "x += MethodCall();", where assignment to 'x' is redundant
// is replaced with "_ = MethodCall();" or "var unused = MethodCall();"
nodeReplacementMap.Add(node.Parent, GetReplacementNodeForCompoundAssignment(node.Parent, newNameNode, editor, syntaxFacts));
}
else
{
var newParentNode = TryUpdateParentOfUpdatedNode(node.Parent, newNameNode, editor, syntaxFacts);
if (newParentNode is object)
{
nodeReplacementMap.Add(node.Parent, newParentNode);
}
else
{
nodeReplacementMap.Add(node, newNameNode);
}
}
}
if (declaredLocal != null)
{
// We have a dead initialization for a local declaration.
// Introduce a new local declaration statement without an initializer for this local.
var declarationStatement = CreateLocalDeclarationStatement(declaredLocal.Type, declaredLocal.Name);
if (isUnusedLocalAssignment)
{
declarationStatement = declarationStatement.WithAdditionalAnnotations(s_unusedLocalDeclarationAnnotation);
}
nodesToAdd.Add((declarationStatement, node));
}
else
{
// We have a dead assignment to a local/parameter, which is not at the declaration site.
// Create a new local declaration for the unused local if both following conditions are met:
// 1. User prefers unused local variables for unused value assignment AND
// 2. Assignment value has side effects and hence cannot be removed.
if (preference == UnusedValuePreference.UnusedLocalVariable && !removeAssignments)
{
var type = semanticModel.GetTypeInfo(node, cancellationToken).Type;
Debug.Assert(type != null);
Debug.Assert(newLocalNameOpt != null);
var declarationStatement = CreateLocalDeclarationStatement(type, newLocalNameOpt);
nodesToAdd.Add((declarationStatement, node));
}
}
}
// Process candidate declaration statements for removal.
foreach (var localDeclarationStatement in candidateDeclarationStatementsForRemoval)
{
// If all the variable declarators for the local declaration statement are being removed,
// we can remove the entire local declaration statement.
if (ShouldRemoveStatement(localDeclarationStatement, out var variables))
{
nodesToRemove.Add(localDeclarationStatement);
nodesToRemove.RemoveRange(variables);
}
}
foreach (var (declarationStatement, node) in nodesToAdd)
{
InsertLocalDeclarationStatement(declarationStatement, node);
}
if (hasAnyUnusedLocalAssignment)
{
// Local declaration statements with no initializer, but non-zero references are candidates for removal
// if the code fix removes all these references.
// We annotate such declaration statements with no initializer abd non-zero references here
// and remove them in post process document pass later, if the code fix did remove all these references.
foreach (var localDeclarationStatement in containingMemberDeclaration.DescendantNodes().OfType<TLocalDeclarationStatementSyntax>())
{
var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
if (variables.Count == 1 &&
syntaxFacts.GetInitializerOfVariableDeclarator(variables[0]) == null &&
!(await IsLocalDeclarationWithNoReferencesAsync(localDeclarationStatement, document, cancellationToken).ConfigureAwait(false)))
{
nodeReplacementMap.Add(localDeclarationStatement, localDeclarationStatement.WithAdditionalAnnotations(s_existingLocalDeclarationWithoutInitializerAnnotation));
}
}
}
foreach (var node in nodesToRemove)
{
var removeOptions = SyntaxGenerator.DefaultRemoveOptions;
// If the leading trivia was not added to a new node, process it now.
if (!processedNodes.Contains(node))
{
// Don't keep trivia if the node is part of a multiple declaration statement.
// e.g. int x = 0, y = 0, z = 0; any white space left behind can cause problems if the declaration gets split apart.
var containingDeclaration = node.GetAncestor<TLocalDeclarationStatementSyntax>();
if (containingDeclaration != null && candidateDeclarationStatementsForRemoval.Contains(containingDeclaration))
{
removeOptions = SyntaxRemoveOptions.KeepNoTrivia;
}
else
{
removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia;
}
}
editor.RemoveNode(node, removeOptions);
}
foreach (var (node, replacement) in nodeReplacementMap)
editor.ReplaceNode(node, replacement.WithAdditionalAnnotations(Formatter.Annotation));
return;
// Local functions.
IEnumerable<(SyntaxNode node, bool isUnusedLocalAssignment)> GetNodesToFix()
{
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
var isUnusedLocalAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsUnusedLocalDiagnostic(diagnostic);
yield return (node, isUnusedLocalAssignment);
}
}
// Mark generated local declaration statement with:
// 1. "s_newLocalDeclarationAnnotation" for post processing in "MoveNewLocalDeclarationsNearReference" below.
// 2. Simplifier annotation so that 'var'/explicit type is correctly added based on user options.
TLocalDeclarationStatementSyntax CreateLocalDeclarationStatement(ITypeSymbol type, string name)
=> (TLocalDeclarationStatementSyntax)editor.Generator.LocalDeclarationStatement(type, name)
.WithLeadingTrivia(syntaxFacts.ElasticCarriageReturnLineFeed)
.WithAdditionalAnnotations(s_newLocalDeclarationStatementAnnotation, Simplifier.Annotation);
void InsertLocalDeclarationStatement(TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode node)
{
// Find the correct place to insert the given declaration statement based on the node's ancestors.
var insertionNode = node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>((n, syntaxFacts) => n.Parent is TSwitchCaseBlockSyntax ||
syntaxFacts.IsExecutableBlock(n.Parent) &&
!(n is TCatchStatementSyntax) &&
!(n is TCatchBlockSyntax),
syntaxFacts);
if (insertionNode is TSwitchCaseLabelOrClauseSyntax)
{
InsertAtStartOfSwitchCaseBlockForDeclarationInCaseLabelOrClause(insertionNode.GetAncestor<TSwitchCaseBlockSyntax>(), editor, declarationStatement);
}
else if (insertionNode is TStatementSyntax)
{
// If the insertion node is being removed, keep the leading trivia (following any directives) with
// the new declaration.
if (nodesToRemove.Contains(insertionNode) && !processedNodes.Contains(insertionNode))
{
// Fix 48070 - The Leading Trivia of the insertion node needs to be filtered
// to only include trivia after Directives (if there are any)
var leadingTrivia = insertionNode.GetLeadingTrivia();
var lastDirective = leadingTrivia.LastOrDefault(t => t.IsDirective);
var lastDirectiveIndex = leadingTrivia.IndexOf(lastDirective);
declarationStatement = declarationStatement.WithLeadingTrivia(leadingTrivia.Skip(lastDirectiveIndex + 1));
// Mark the node as processed so that the trivia only gets added once.
processedNodes.Add(insertionNode);
}
editor.InsertBefore(insertionNode, declarationStatement);
}
}
bool ShouldRemoveStatement(TLocalDeclarationStatementSyntax localDeclarationStatement, out SeparatedSyntaxList<SyntaxNode> variables)
{
Debug.Assert(removeAssignments);
Debug.Assert(localDeclarationStatement != null);
// We should remove the entire local declaration statement if all its variables are marked for removal.
variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
foreach (var variable in variables)
{
if (!nodesToRemove.Contains(variable))
{
return false;
}
}
return true;
}
}
protected abstract TLocalDeclarationStatementSyntax GetCandidateLocalDeclarationForRemoval(TVariableDeclaratorSyntax declarator);
private async Task<SyntaxNode> PostProcessDocumentAsync(
Document document,
SyntaxNode currentRoot,
string diagnosticId,
UnusedValuePreference preference,
CancellationToken cancellationToken)
{
// If we added discard assignments, replace all discard variable declarations in
// this method with discard assignments, i.e. "var _ = M();" is replaced with "_ = M();"
// This is done to prevent compiler errors where the existing method has a discard
// variable declaration at a line following the one we added a discard assignment in our fix.
if (preference == UnusedValuePreference.DiscardVariable)
{
currentRoot = await PostProcessDocumentCoreAsync(
ReplaceDiscardDeclarationsWithAssignmentsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
}
// If we added new variable declaration statements, move these as close as possible to their
// first reference site.
if (NeedsToMoveNewLocalDeclarationsNearReference(diagnosticId))
{
currentRoot = await PostProcessDocumentCoreAsync(
AdjustLocalDeclarationsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
}
return currentRoot;
}
private static async Task<SyntaxNode> PostProcessDocumentCoreAsync(
Func<SyntaxNode, Document, CancellationToken, Task<SyntaxNode>> processMemberDeclarationAsync,
SyntaxNode currentRoot,
Document document,
CancellationToken cancellationToken)
{
// Process each member declaration which had atleast one diagnostic reported in the original tree
// and hence was annotated with "s_memberAnnotation" for post processing.
var newDocument = document.WithSyntaxRoot(currentRoot);
var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
using var _1 = PooledDictionary<SyntaxNode, SyntaxNode>.GetInstance(out var memberDeclReplacementsMap);
foreach (var memberDecl in newRoot.DescendantNodes().Where(n => n.HasAnnotation(s_memberAnnotation)))
{
var newMemberDecl = await processMemberDeclarationAsync(memberDecl, newDocument, cancellationToken).ConfigureAwait(false);
memberDeclReplacementsMap.Add(memberDecl, newMemberDecl);
}
return newRoot.ReplaceNodes(memberDeclReplacementsMap.Keys,
computeReplacementNode: (node, _) => memberDeclReplacementsMap[node]);
}
/// <summary>
/// Returns an updated <paramref name="memberDeclaration"/> with all the
/// local declarations named '_' converted to simple assignments to discard.
/// For example, <code>int _ = Computation();</code> is converted to
/// <code>_ = Computation();</code>.
/// This is needed to prevent the code fix/FixAll from generating code with
/// multiple local variables named '_', which is a compiler error.
/// </summary>
private async Task<SyntaxNode> ReplaceDiscardDeclarationsWithAssignmentsAsync(SyntaxNode memberDeclaration, Document document, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IReplaceDiscardDeclarationsWithAssignmentsService>();
if (service == null)
{
return memberDeclaration;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await service.ReplaceAsync(memberDeclaration, semanticModel, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an updated <paramref name="memberDeclaration"/> with all the new
/// local declaration statements annotated with <see cref="s_newLocalDeclarationStatementAnnotation"/>
/// moved closer to first reference and all the existing
/// local declaration statements annotated with <see cref="s_existingLocalDeclarationWithoutInitializerAnnotation"/>
/// whose declared local is no longer used removed.
/// </summary>
private async Task<SyntaxNode> AdjustLocalDeclarationsAsync(
SyntaxNode memberDeclaration,
Document document,
CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IMoveDeclarationNearReferenceService>();
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var originalDocument = document;
var originalDeclStatementsToMoveOrRemove = memberDeclaration.DescendantNodes()
.Where(n => n.HasAnnotation(s_newLocalDeclarationStatementAnnotation) ||
n.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation))
.ToImmutableArray();
if (originalDeclStatementsToMoveOrRemove.IsEmpty)
{
return memberDeclaration;
}
// Moving declarations closer to a reference can lead to conflicting edits.
// So, we track all the declaration statements to be moved upfront, and update
// the root, document, editor and memberDeclaration for every edit.
// Finally, we apply replace the memberDeclaration in the originalEditor as a single edit.
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var rootWithTrackedNodes = root.TrackNodes(originalDeclStatementsToMoveOrRemove);
// Run formatter prior to invoking IMoveDeclarationNearReferenceService.
rootWithTrackedNodes = Formatter.Format(rootWithTrackedNodes, originalDeclStatementsToMoveOrRemove.Select(s => s.Span), document.Project.Solution.Workspace, cancellationToken: cancellationToken);
document = document.WithSyntaxRoot(rootWithTrackedNodes);
await OnDocumentUpdatedAsync().ConfigureAwait(false);
foreach (TLocalDeclarationStatementSyntax originalDeclStatement in originalDeclStatementsToMoveOrRemove)
{
// Get the current declaration statement.
var declStatement = memberDeclaration.GetCurrentNode(originalDeclStatement);
var documentUpdated = false;
// Check if the variable declaration is unused after all the fixes, and hence can be removed.
if (await TryRemoveUnusedLocalAsync(declStatement, originalDeclStatement).ConfigureAwait(false))
{
documentUpdated = true;
}
else if (declStatement.HasAnnotation(s_newLocalDeclarationStatementAnnotation))
{
// Otherwise, move the declaration closer to the first reference if possible.
if (await service.CanMoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false))
{
document = await service.MoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false);
documentUpdated = true;
}
}
if (documentUpdated)
{
await OnDocumentUpdatedAsync().ConfigureAwait(false);
}
}
return memberDeclaration;
// Local functions.
async Task OnDocumentUpdatedAsync()
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
memberDeclaration = syntaxFacts.GetContainingMemberDeclaration(root, memberDeclaration.SpanStart);
}
async Task<bool> TryRemoveUnusedLocalAsync(TLocalDeclarationStatementSyntax newDecl, TLocalDeclarationStatementSyntax originalDecl)
{
// If we introduced this new local declaration statement while computing the code fix,
// but all it's existing references were removed as part of FixAll, then we
// can remove the unncessary local declaration statement.
// Additionally, if this is an existing local declaration without an initializer,
// such that the local has no references anymore, we can remove it.
if (newDecl.HasAnnotation(s_unusedLocalDeclarationAnnotation) ||
newDecl.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation))
{
// Check if we have no references to local in fixed code.
if (await IsLocalDeclarationWithNoReferencesAsync(newDecl, document, cancellationToken).ConfigureAwait(false))
{
document = document.WithSyntaxRoot(
root.RemoveNode(newDecl, SyntaxGenerator.DefaultRemoveOptions | SyntaxRemoveOptions.KeepLeadingTrivia));
return true;
}
}
return false;
}
}
private static async Task<bool> IsLocalDeclarationWithNoReferencesAsync(
TLocalDeclarationStatementSyntax declStatement,
Document document,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var localDeclarationOperation = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(declStatement, cancellationToken);
var local = localDeclarationOperation.GetDeclaredVariables().Single();
// Check if the declared variable has no references in fixed code.
var referencedSymbols = await SymbolFinder.FindReferencesAsync(local, document.Project.Solution, cancellationToken).ConfigureAwait(false);
return referencedSymbols.Count() == 1 &&
referencedSymbols.Single().Locations.IsEmpty();
}
private sealed class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(title, createChangedDocument, equivalenceKey)
{
}
}
protected sealed class UniqueVariableNameGenerator : IDisposable
{
private readonly SyntaxNode _memberDeclaration;
private readonly SemanticModel _semanticModel;
private readonly ISemanticFactsService _semanticFacts;
private readonly CancellationToken _cancellationToken;
private readonly PooledHashSet<string> _usedNames;
public UniqueVariableNameGenerator(
SyntaxNode memberDeclaration,
SemanticModel semanticModel,
ISemanticFactsService semanticFacts,
CancellationToken cancellationToken)
{
_memberDeclaration = memberDeclaration;
_semanticModel = semanticModel;
_semanticFacts = semanticFacts;
_cancellationToken = cancellationToken;
_usedNames = PooledHashSet<string>.GetInstance();
}
public SyntaxToken GenerateUniqueNameAtSpanStart(SyntaxNode node)
{
var nameToken = _semanticFacts.GenerateUniqueName(_semanticModel, node, _memberDeclaration, "unused", _usedNames, _cancellationToken);
_usedNames.Add(nameToken.ValueText);
return nameToken;
}
public void Dispose() => _usedNames.Free();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.MoveDeclarationNearReference;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.ReplaceDiscardDeclarationsWithAssignments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues
{
/// <summary>
/// Code fixer for unused expression value diagnostics reported by <see cref="AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer"/>.
/// We provide following code fixes:
/// 1. If the unused value assigned to a local/parameter has no side-effects,
/// we recommend removing the assignment. We consider an expression value to have no side effects
/// if one of the following is true:
/// 1. Value is a compile time constant.
/// 2. Value is a local or parameter reference.
/// 3. Value is a field reference with no or implicit this instance.
/// 2. Otherwise, if user preference is set to DiscardVariable, and project's
/// language version supports discard variable, we recommend assigning the value to discard.
/// 3. Otherwise, we recommend assigning the value to a new unused local variable which has no reads.
/// </summary>
internal abstract class AbstractRemoveUnusedValuesCodeFixProvider<TExpressionSyntax, TStatementSyntax, TBlockSyntax,
TExpressionStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax, TForEachStatementSyntax,
TSwitchCaseBlockSyntax, TSwitchCaseLabelOrClauseSyntax, TCatchStatementSyntax, TCatchBlockSyntax>
: SyntaxEditorBasedCodeFixProvider
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TBlockSyntax : TStatementSyntax
where TExpressionStatementSyntax : TStatementSyntax
where TLocalDeclarationStatementSyntax : TStatementSyntax
where TForEachStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
where TSwitchCaseBlockSyntax : SyntaxNode
where TSwitchCaseLabelOrClauseSyntax : SyntaxNode
{
private static readonly SyntaxAnnotation s_memberAnnotation = new();
private static readonly SyntaxAnnotation s_newLocalDeclarationStatementAnnotation = new();
private static readonly SyntaxAnnotation s_unusedLocalDeclarationAnnotation = new();
private static readonly SyntaxAnnotation s_existingLocalDeclarationWithoutInitializerAnnotation = new();
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.ExpressionValueIsUnusedDiagnosticId,
IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;
/// <summary>
/// Method to update the identifier token for the local/parameter declaration or reference
/// that was flagged as an unused value write by the analyzer.
/// Returns null if the provided node is not one of the handled node kinds.
/// Otherwise, returns the new node with updated identifier.
/// </summary>
/// <param name="node">Flaggged node containing the identifier token to be replaced.</param>
/// <param name="newName">New identifier token</param>
protected abstract SyntaxNode TryUpdateNameForFlaggedNode(SyntaxNode node, SyntaxToken newName);
/// <summary>
/// Gets the identifier token for the iteration variable of the given foreach statement node.
/// </summary>
protected abstract SyntaxToken GetForEachStatementIdentifier(TForEachStatementSyntax node);
/// <summary>
/// Wraps the given statements within a block statement.
/// Note this method is invoked when replacing a statement that is parented by a non-block statement syntax.
/// </summary>
protected abstract TBlockSyntax WrapWithBlockIfNecessary(IEnumerable<TStatementSyntax> statements);
/// <summary>
/// Inserts the given declaration statement at the start of the given switch case block.
/// </summary>
protected abstract void InsertAtStartOfSwitchCaseBlockForDeclarationInCaseLabelOrClause(TSwitchCaseBlockSyntax switchCaseBlock, SyntaxEditor editor, TLocalDeclarationStatementSyntax declarationStatement);
/// <summary>
/// Gets the replacement node for a compound assignment expression whose
/// assigned value is redundant.
/// For example, "x += MethodCall()", where assignment to 'x' is redundant
/// is replaced with "_ = MethodCall()" or "var unused = MethodCall()"
/// </summary>
protected abstract SyntaxNode GetReplacementNodeForCompoundAssignment(
SyntaxNode originalCompoundAssignment,
SyntaxNode newAssignmentTarget,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts);
/// <summary>
/// Rewrite the parent of a node which was rewritted by <see cref="TryUpdateNameForFlaggedNode"/>.
/// </summary>
/// <param name="parent">The original parent of the node rewritten by <see cref="TryUpdateNameForFlaggedNode"/>.</param>
/// <param name="newNameNode">The rewritten node produced by <see cref="TryUpdateNameForFlaggedNode"/>.</param>
/// <param name="editor">The syntax editor for the code fix.</param>
/// <param name="syntaxFacts">The syntax facts for the current language.</param>
/// <returns>The replacement node to use in the rewritten syntax tree; otherwise, <see langword="null"/> to only
/// rewrite the node originally rewritten by <see cref="TryUpdateNameForFlaggedNode"/>.</returns>
protected virtual SyntaxNode TryUpdateParentOfUpdatedNode(SyntaxNode parent, SyntaxNode newNameNode, SyntaxEditor editor, ISyntaxFacts syntaxFacts)
{
return null;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics[0];
if (!AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var preference))
{
return;
}
var isRemovableAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic);
string title;
if (isRemovableAssignment)
{
// Recommend removing the redundant constant value assignment.
title = CodeFixesResources.Remove_redundant_assignment;
}
else
{
// Recommend using discard/unused local for redundant non-constant assignment.
switch (preference)
{
case UnusedValuePreference.DiscardVariable:
if (IsForEachIterationVariableDiagnostic(diagnostic, context.Document, context.CancellationToken))
{
// Do not offer a fix to replace unused foreach iteration variable with discard.
// User should probably replace it with a for loop based on the collection length.
return;
}
title = CodeFixesResources.Use_discard_underscore;
// Check if this is compound assignment which is not parented by an expression statement,
// for example "return x += M();" OR "=> x ??= new C();"
// If so, we will be replacing this compound assignment with the underlying binary operation.
// For the above examples, it will be "return x + M();" AND "=> x ?? new C();" respectively.
// For these cases, we want to show the title as "Remove redundant assignment" instead of "Use discard _".
var syntaxFacts = context.Document.GetLanguageService<ISyntaxFactsService>();
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span, getInnermostNodeForTie: true);
if (syntaxFacts.IsLeftSideOfCompoundAssignment(node) &&
!syntaxFacts.IsExpressionStatement(node.Parent))
{
title = CodeFixesResources.Remove_redundant_assignment;
}
break;
case UnusedValuePreference.UnusedLocalVariable:
title = CodeFixesResources.Use_discarded_local;
break;
default:
return;
}
}
context.RegisterCodeFix(
new MyCodeAction(
title,
c => FixAsync(context.Document, diagnostic, c),
equivalenceKey: GetEquivalenceKey(preference, isRemovableAssignment)),
diagnostic);
return;
}
private static bool IsForEachIterationVariableDiagnostic(Diagnostic diagnostic, Document document, CancellationToken cancellationToken)
{
// Do not offer a fix to replace unused foreach iteration variable with discard.
// User should probably replace it with a for loop based on the collection length.
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
return syntaxFacts.IsForEachStatement(diagnostic.Location.FindNode(cancellationToken));
}
private static string GetEquivalenceKey(UnusedValuePreference preference, bool isRemovableAssignment)
=> preference.ToString() + isRemovableAssignment;
private static string GetEquivalenceKey(Diagnostic diagnostic)
{
if (!AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var preference))
{
return string.Empty;
}
var isRemovableAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic);
return GetEquivalenceKey(preference, isRemovableAssignment);
}
/// <summary>
/// Flag to indicate if the code fix can introduce local declaration statements
/// that need to be moved closer to the first reference of the declared variable.
/// This is currently only possible for the unused value assignment fix.
/// </summary>
private static bool NeedsToMoveNewLocalDeclarationsNearReference(string diagnosticId)
=> diagnosticId == IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string equivalenceKey, CancellationToken cancellationToken)
{
return equivalenceKey == GetEquivalenceKey(diagnostic) &&
!IsForEachIterationVariableDiagnostic(diagnostic, document, cancellationToken);
}
private static IEnumerable<IGrouping<SyntaxNode, Diagnostic>> GetDiagnosticsGroupedByMember(
ImmutableArray<Diagnostic> diagnostics,
ISyntaxFactsService syntaxFacts,
SyntaxNode root,
out string diagnosticId,
out UnusedValuePreference preference,
out bool removeAssignments)
{
diagnosticId = diagnostics[0].Id;
var success = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostics[0], out preference);
Debug.Assert(success);
removeAssignments = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostics[0]);
#if DEBUG
foreach (var diagnostic in diagnostics)
{
Debug.Assert(diagnosticId == diagnostic.Id);
Debug.Assert(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var diagnosticPreference) &&
diagnosticPreference == preference);
Debug.Assert(removeAssignments == AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic));
}
#endif
return GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root);
}
private static IEnumerable<IGrouping<SyntaxNode, Diagnostic>> GetDiagnosticsGroupedByMember(
ImmutableArray<Diagnostic> diagnostics,
ISyntaxFactsService syntaxFacts,
SyntaxNode root)
=> diagnostics.GroupBy(d => syntaxFacts.GetContainingMemberDeclaration(root, d.Location.SourceSpan.Start));
private static async Task<Document> PreprocessDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
// Track all the member declaration nodes that have diagnostics.
// We will post process all these tracked nodes after applying the fix (see "PostProcessDocumentAsync" below in this source file).
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var memberDeclarations = GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root).Select(g => g.Key);
root = root.ReplaceNodes(memberDeclarations, computeReplacementNode: (_, n) => n.WithAdditionalAnnotations(s_memberAnnotation));
return document.WithSyntaxRoot(root);
}
protected sealed override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
document = await PreprocessDocumentAsync(document, diagnostics, cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var originalEditor = editor;
editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
try
{
// We compute the code fix in two passes:
// 1. The first pass groups the diagnostics to fix by containing member declaration and
// computes and applies the core code fixes. Grouping is done to ensure we choose
// the most appropriate name for new unused local declarations, which can clash
// with existing local declarations in the method body.
// 2. Second pass (PostProcessDocumentAsync) performs additional syntax manipulations
// for the fixes produced from from first pass:
// a. Replace discard declarations, such as "var _ = M();" that conflict with newly added
// discard assignments, with discard assignments of the form "_ = M();"
// b. Move newly introduced local declaration statements closer to the local variable's
// first reference.
// Get diagnostics grouped by member.
var diagnosticsGroupedByMember = GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root,
out var diagnosticId, out var preference, out var removeAssignments);
// First pass to compute and apply the core code fixes.
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnosticsToFix in diagnosticsGroupedByMember)
{
var containingMemberDeclaration = diagnosticsToFix.Key;
using var nameGenerator = new UniqueVariableNameGenerator(containingMemberDeclaration, semanticModel, semanticFacts, cancellationToken);
await FixAllAsync(diagnosticId, diagnosticsToFix.Select(d => d), document, semanticModel, root, containingMemberDeclaration, preference,
removeAssignments, nameGenerator, editor, syntaxFacts, cancellationToken).ConfigureAwait(false);
}
// Second pass to post process the document.
var currentRoot = editor.GetChangedRoot();
var newRoot = await PostProcessDocumentAsync(document, currentRoot,
diagnosticId, preference, cancellationToken).ConfigureAwait(false);
if (currentRoot != newRoot)
{
editor.ReplaceNode(root, newRoot);
}
}
finally
{
originalEditor.ReplaceNode(originalEditor.OriginalRoot, editor.GetChangedRoot());
}
}
private async Task FixAllAsync(
string diagnosticId,
IEnumerable<Diagnostic> diagnostics,
Document document,
SemanticModel semanticModel,
SyntaxNode root,
SyntaxNode containingMemberDeclaration,
UnusedValuePreference preference,
bool removeAssignments,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
switch (diagnosticId)
{
case IDEDiagnosticIds.ExpressionValueIsUnusedDiagnosticId:
// Make sure the inner diagnostics are placed first
FixAllExpressionValueIsUnusedDiagnostics(diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start), semanticModel, root,
preference, nameGenerator, editor, syntaxFacts);
break;
case IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId:
// Make sure the diagnostics are placed in order.
// Example:
// int a = 0; int b = 1;
// After fix it would be int a; int b;
await FixAllValueAssignedIsUnusedDiagnosticsAsync(diagnostics.OrderBy(d => d.Location.SourceSpan.Start), document, semanticModel, root, containingMemberDeclaration,
preference, removeAssignments, nameGenerator, editor, syntaxFacts, cancellationToken).ConfigureAwait(false);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private static void FixAllExpressionValueIsUnusedDiagnostics(
IOrderedEnumerable<Diagnostic> diagnostics,
SemanticModel semanticModel,
SyntaxNode root,
UnusedValuePreference preference,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts)
{
// This method applies the code fix for diagnostics reported for expression statement dropping values.
// We replace each flagged expression statement with an assignment to a discard variable or a new unused local,
// based on the user's preference.
// Note: The diagnostic order here should be inner first and outer second.
// Example: Foo1(() => { Foo2(); })
// Foo2() should be the first in this case.
foreach (var diagnostic in diagnostics)
{
var expressionStatement = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<TExpressionStatementSyntax>();
if (expressionStatement == null)
{
continue;
}
switch (preference)
{
case UnusedValuePreference.DiscardVariable:
Debug.Assert(semanticModel.Language != LanguageNames.VisualBasic);
var expression = syntaxFacts.GetExpressionOfExpressionStatement(expressionStatement);
editor.ReplaceNode(expression, (node, generator) =>
{
var discardAssignmentExpression = (TExpressionSyntax)generator.AssignmentStatement(
left: generator.IdentifierName(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName),
right: node.WithoutTrivia())
.WithTriviaFrom(node)
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
return discardAssignmentExpression;
});
break;
case UnusedValuePreference.UnusedLocalVariable:
var name = nameGenerator.GenerateUniqueNameAtSpanStart(expressionStatement).ValueText;
editor.ReplaceNode(expressionStatement, (node, generator) =>
{
var expression = syntaxFacts.GetExpressionOfExpressionStatement(node);
// Add Simplifier annotation so that 'var'/explicit type is correctly added based on user options.
var localDecl = editor.Generator.LocalDeclarationStatement(
name: name,
initializer: expression.WithoutLeadingTrivia())
.WithTriviaFrom(node)
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
return localDecl;
});
break;
}
}
}
private async Task FixAllValueAssignedIsUnusedDiagnosticsAsync(
IOrderedEnumerable<Diagnostic> diagnostics,
Document document,
SemanticModel semanticModel,
SyntaxNode root,
SyntaxNode containingMemberDeclaration,
UnusedValuePreference preference,
bool removeAssignments,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
// This method applies the code fix for diagnostics reported for unused value assignments to local/parameter.
// The actual code fix depends on whether or not the right hand side of the assignment has side effects.
// For example, if the right hand side is a constant or a reference to a local/parameter, then it has no side effects.
// The lack of side effects is indicated by the "removeAssignments" parameter for this function.
// If the right hand side has no side effects, then we can replace the assignments with variable declarations that have no initializer
// or completely remove the statement.
// If the right hand side does have side effects, we replace the identifier token for unused value assignment with
// a new identifier token (either discard '_' or new unused local variable name).
// For both the above cases, if the original diagnostic was reported on a local declaration, i.e. redundant initialization
// at declaration, then we also add a new variable declaration statement without initializer for this local.
using var _1 = PooledDictionary<SyntaxNode, SyntaxNode>.GetInstance(out var nodeReplacementMap);
using var _2 = PooledHashSet<SyntaxNode>.GetInstance(out var nodesToRemove);
using var _3 = PooledHashSet<(TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode node)>.GetInstance(out var nodesToAdd);
// Indicates if the node's trivia was processed.
using var _4 = PooledHashSet<SyntaxNode>.GetInstance(out var processedNodes);
using var _5 = PooledHashSet<TLocalDeclarationStatementSyntax>.GetInstance(out var candidateDeclarationStatementsForRemoval);
var hasAnyUnusedLocalAssignment = false;
foreach (var (node, isUnusedLocalAssignment) in GetNodesToFix())
{
hasAnyUnusedLocalAssignment |= isUnusedLocalAssignment;
var declaredLocal = semanticModel.GetDeclaredSymbol(node, cancellationToken) as ILocalSymbol;
if (declaredLocal == null && node.Parent is TCatchStatementSyntax)
{
declaredLocal = semanticModel.GetDeclaredSymbol(node.Parent, cancellationToken) as ILocalSymbol;
}
string newLocalNameOpt = null;
if (removeAssignments)
{
// Removable assignment or initialization, such that right hand side has no side effects.
if (declaredLocal != null)
{
// Redundant initialization.
// For example, "int a = 0;"
var variableDeclarator = node.FirstAncestorOrSelf<TVariableDeclaratorSyntax>();
Debug.Assert(variableDeclarator != null);
nodesToRemove.Add(variableDeclarator);
// Local declaration statement containing the declarator might be a candidate for removal if all its variables get marked for removal.
var candidate = GetCandidateLocalDeclarationForRemoval(variableDeclarator);
if (candidate != null)
{
candidateDeclarationStatementsForRemoval.Add(candidate);
}
}
else
{
// Redundant assignment or increment/decrement.
if (syntaxFacts.IsOperandOfIncrementOrDecrementExpression(node))
{
// For example, C# increment operation "a++;"
Debug.Assert(node.Parent.Parent is TExpressionStatementSyntax);
nodesToRemove.Add(node.Parent.Parent);
}
else
{
Debug.Assert(syntaxFacts.IsLeftSideOfAnyAssignment(node));
if (node.Parent is TStatementSyntax)
{
// For example, VB simple assignment statement "a = 0"
nodesToRemove.Add(node.Parent);
}
else if (node.Parent is TExpressionSyntax && node.Parent.Parent is TExpressionStatementSyntax)
{
// For example, C# simple assignment statement "a = 0;"
nodesToRemove.Add(node.Parent.Parent);
}
else
{
// For example, C# nested assignment statement "a = b = 0;", where assignment to 'b' is redundant.
// We replace the node with "a = 0;"
nodeReplacementMap.Add(node.Parent, syntaxFacts.GetRightHandSideOfAssignment(node.Parent));
}
}
}
}
else
{
// Value initialization/assignment where the right hand side may have side effects,
// and hence needs to be preserved in fixed code.
// For example, "x = MethodCall();" is replaced with "_ = MethodCall();" or "var unused = MethodCall();"
// Replace the flagged variable's indentifier token with new named, based on user's preference.
var newNameToken = preference == UnusedValuePreference.DiscardVariable
? document.GetRequiredLanguageService<SyntaxGeneratorInternal>().Identifier(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName)
: nameGenerator.GenerateUniqueNameAtSpanStart(node);
newLocalNameOpt = newNameToken.ValueText;
var newNameNode = TryUpdateNameForFlaggedNode(node, newNameToken);
if (newNameNode == null)
{
continue;
}
// Is this is compound assignment?
if (syntaxFacts.IsLeftSideOfAnyAssignment(node) && !syntaxFacts.IsLeftSideOfAssignment(node))
{
// Compound assignment is changed to simple assignment.
// For example, "x += MethodCall();", where assignment to 'x' is redundant
// is replaced with "_ = MethodCall();" or "var unused = MethodCall();"
nodeReplacementMap.Add(node.Parent, GetReplacementNodeForCompoundAssignment(node.Parent, newNameNode, editor, syntaxFacts));
}
else
{
var newParentNode = TryUpdateParentOfUpdatedNode(node.Parent, newNameNode, editor, syntaxFacts);
if (newParentNode is object)
{
nodeReplacementMap.Add(node.Parent, newParentNode);
}
else
{
nodeReplacementMap.Add(node, newNameNode);
}
}
}
if (declaredLocal != null)
{
// We have a dead initialization for a local declaration.
// Introduce a new local declaration statement without an initializer for this local.
var declarationStatement = CreateLocalDeclarationStatement(declaredLocal.Type, declaredLocal.Name);
if (isUnusedLocalAssignment)
{
declarationStatement = declarationStatement.WithAdditionalAnnotations(s_unusedLocalDeclarationAnnotation);
}
nodesToAdd.Add((declarationStatement, node));
}
else
{
// We have a dead assignment to a local/parameter, which is not at the declaration site.
// Create a new local declaration for the unused local if both following conditions are met:
// 1. User prefers unused local variables for unused value assignment AND
// 2. Assignment value has side effects and hence cannot be removed.
if (preference == UnusedValuePreference.UnusedLocalVariable && !removeAssignments)
{
var type = semanticModel.GetTypeInfo(node, cancellationToken).Type;
Debug.Assert(type != null);
Debug.Assert(newLocalNameOpt != null);
var declarationStatement = CreateLocalDeclarationStatement(type, newLocalNameOpt);
nodesToAdd.Add((declarationStatement, node));
}
}
}
// Process candidate declaration statements for removal.
foreach (var localDeclarationStatement in candidateDeclarationStatementsForRemoval)
{
// If all the variable declarators for the local declaration statement are being removed,
// we can remove the entire local declaration statement.
if (ShouldRemoveStatement(localDeclarationStatement, out var variables))
{
nodesToRemove.Add(localDeclarationStatement);
nodesToRemove.RemoveRange(variables);
}
}
foreach (var (declarationStatement, node) in nodesToAdd)
{
InsertLocalDeclarationStatement(declarationStatement, node);
}
if (hasAnyUnusedLocalAssignment)
{
// Local declaration statements with no initializer, but non-zero references are candidates for removal
// if the code fix removes all these references.
// We annotate such declaration statements with no initializer abd non-zero references here
// and remove them in post process document pass later, if the code fix did remove all these references.
foreach (var localDeclarationStatement in containingMemberDeclaration.DescendantNodes().OfType<TLocalDeclarationStatementSyntax>())
{
var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
if (variables.Count == 1 &&
syntaxFacts.GetInitializerOfVariableDeclarator(variables[0]) == null &&
!(await IsLocalDeclarationWithNoReferencesAsync(localDeclarationStatement, document, cancellationToken).ConfigureAwait(false)))
{
nodeReplacementMap.Add(localDeclarationStatement, localDeclarationStatement.WithAdditionalAnnotations(s_existingLocalDeclarationWithoutInitializerAnnotation));
}
}
}
foreach (var node in nodesToRemove)
{
var removeOptions = SyntaxGenerator.DefaultRemoveOptions;
// If the leading trivia was not added to a new node, process it now.
if (!processedNodes.Contains(node))
{
// Don't keep trivia if the node is part of a multiple declaration statement.
// e.g. int x = 0, y = 0, z = 0; any white space left behind can cause problems if the declaration gets split apart.
var containingDeclaration = node.GetAncestor<TLocalDeclarationStatementSyntax>();
if (containingDeclaration != null && candidateDeclarationStatementsForRemoval.Contains(containingDeclaration))
{
removeOptions = SyntaxRemoveOptions.KeepNoTrivia;
}
else
{
removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia;
}
}
editor.RemoveNode(node, removeOptions);
}
foreach (var (node, replacement) in nodeReplacementMap)
editor.ReplaceNode(node, replacement.WithAdditionalAnnotations(Formatter.Annotation));
return;
// Local functions.
IEnumerable<(SyntaxNode node, bool isUnusedLocalAssignment)> GetNodesToFix()
{
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
var isUnusedLocalAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsUnusedLocalDiagnostic(diagnostic);
yield return (node, isUnusedLocalAssignment);
}
}
// Mark generated local declaration statement with:
// 1. "s_newLocalDeclarationAnnotation" for post processing in "MoveNewLocalDeclarationsNearReference" below.
// 2. Simplifier annotation so that 'var'/explicit type is correctly added based on user options.
TLocalDeclarationStatementSyntax CreateLocalDeclarationStatement(ITypeSymbol type, string name)
=> (TLocalDeclarationStatementSyntax)editor.Generator.LocalDeclarationStatement(type, name)
.WithLeadingTrivia(syntaxFacts.ElasticCarriageReturnLineFeed)
.WithAdditionalAnnotations(s_newLocalDeclarationStatementAnnotation, Simplifier.Annotation);
void InsertLocalDeclarationStatement(TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode node)
{
// Find the correct place to insert the given declaration statement based on the node's ancestors.
var insertionNode = node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>((n, syntaxFacts) => n.Parent is TSwitchCaseBlockSyntax ||
syntaxFacts.IsExecutableBlock(n.Parent) &&
!(n is TCatchStatementSyntax) &&
!(n is TCatchBlockSyntax),
syntaxFacts);
if (insertionNode is TSwitchCaseLabelOrClauseSyntax)
{
InsertAtStartOfSwitchCaseBlockForDeclarationInCaseLabelOrClause(insertionNode.GetAncestor<TSwitchCaseBlockSyntax>(), editor, declarationStatement);
}
else if (insertionNode is TStatementSyntax)
{
// If the insertion node is being removed, keep the leading trivia (following any directives) with
// the new declaration.
if (nodesToRemove.Contains(insertionNode) && !processedNodes.Contains(insertionNode))
{
// Fix 48070 - The Leading Trivia of the insertion node needs to be filtered
// to only include trivia after Directives (if there are any)
var leadingTrivia = insertionNode.GetLeadingTrivia();
var lastDirective = leadingTrivia.LastOrDefault(t => t.IsDirective);
var lastDirectiveIndex = leadingTrivia.IndexOf(lastDirective);
declarationStatement = declarationStatement.WithLeadingTrivia(leadingTrivia.Skip(lastDirectiveIndex + 1));
// Mark the node as processed so that the trivia only gets added once.
processedNodes.Add(insertionNode);
}
editor.InsertBefore(insertionNode, declarationStatement);
}
}
bool ShouldRemoveStatement(TLocalDeclarationStatementSyntax localDeclarationStatement, out SeparatedSyntaxList<SyntaxNode> variables)
{
Debug.Assert(removeAssignments);
Debug.Assert(localDeclarationStatement != null);
// We should remove the entire local declaration statement if all its variables are marked for removal.
variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
foreach (var variable in variables)
{
if (!nodesToRemove.Contains(variable))
{
return false;
}
}
return true;
}
}
protected abstract TLocalDeclarationStatementSyntax GetCandidateLocalDeclarationForRemoval(TVariableDeclaratorSyntax declarator);
private async Task<SyntaxNode> PostProcessDocumentAsync(
Document document,
SyntaxNode currentRoot,
string diagnosticId,
UnusedValuePreference preference,
CancellationToken cancellationToken)
{
// If we added discard assignments, replace all discard variable declarations in
// this method with discard assignments, i.e. "var _ = M();" is replaced with "_ = M();"
// This is done to prevent compiler errors where the existing method has a discard
// variable declaration at a line following the one we added a discard assignment in our fix.
if (preference == UnusedValuePreference.DiscardVariable)
{
currentRoot = await PostProcessDocumentCoreAsync(
ReplaceDiscardDeclarationsWithAssignmentsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
}
// If we added new variable declaration statements, move these as close as possible to their
// first reference site.
if (NeedsToMoveNewLocalDeclarationsNearReference(diagnosticId))
{
currentRoot = await PostProcessDocumentCoreAsync(
AdjustLocalDeclarationsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
}
return currentRoot;
}
private static async Task<SyntaxNode> PostProcessDocumentCoreAsync(
Func<SyntaxNode, Document, CancellationToken, Task<SyntaxNode>> processMemberDeclarationAsync,
SyntaxNode currentRoot,
Document document,
CancellationToken cancellationToken)
{
// Process each member declaration which had atleast one diagnostic reported in the original tree
// and hence was annotated with "s_memberAnnotation" for post processing.
var newDocument = document.WithSyntaxRoot(currentRoot);
var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
using var _1 = PooledDictionary<SyntaxNode, SyntaxNode>.GetInstance(out var memberDeclReplacementsMap);
foreach (var memberDecl in newRoot.DescendantNodes().Where(n => n.HasAnnotation(s_memberAnnotation)))
{
var newMemberDecl = await processMemberDeclarationAsync(memberDecl, newDocument, cancellationToken).ConfigureAwait(false);
memberDeclReplacementsMap.Add(memberDecl, newMemberDecl);
}
return newRoot.ReplaceNodes(memberDeclReplacementsMap.Keys,
computeReplacementNode: (node, _) => memberDeclReplacementsMap[node]);
}
/// <summary>
/// Returns an updated <paramref name="memberDeclaration"/> with all the
/// local declarations named '_' converted to simple assignments to discard.
/// For example, <code>int _ = Computation();</code> is converted to
/// <code>_ = Computation();</code>.
/// This is needed to prevent the code fix/FixAll from generating code with
/// multiple local variables named '_', which is a compiler error.
/// </summary>
private async Task<SyntaxNode> ReplaceDiscardDeclarationsWithAssignmentsAsync(SyntaxNode memberDeclaration, Document document, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IReplaceDiscardDeclarationsWithAssignmentsService>();
if (service == null)
{
return memberDeclaration;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await service.ReplaceAsync(memberDeclaration, semanticModel, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an updated <paramref name="memberDeclaration"/> with all the new
/// local declaration statements annotated with <see cref="s_newLocalDeclarationStatementAnnotation"/>
/// moved closer to first reference and all the existing
/// local declaration statements annotated with <see cref="s_existingLocalDeclarationWithoutInitializerAnnotation"/>
/// whose declared local is no longer used removed.
/// </summary>
private async Task<SyntaxNode> AdjustLocalDeclarationsAsync(
SyntaxNode memberDeclaration,
Document document,
CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IMoveDeclarationNearReferenceService>();
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var originalDocument = document;
var originalDeclStatementsToMoveOrRemove = memberDeclaration.DescendantNodes()
.Where(n => n.HasAnnotation(s_newLocalDeclarationStatementAnnotation) ||
n.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation))
.ToImmutableArray();
if (originalDeclStatementsToMoveOrRemove.IsEmpty)
{
return memberDeclaration;
}
// Moving declarations closer to a reference can lead to conflicting edits.
// So, we track all the declaration statements to be moved upfront, and update
// the root, document, editor and memberDeclaration for every edit.
// Finally, we apply replace the memberDeclaration in the originalEditor as a single edit.
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var rootWithTrackedNodes = root.TrackNodes(originalDeclStatementsToMoveOrRemove);
// Run formatter prior to invoking IMoveDeclarationNearReferenceService.
rootWithTrackedNodes = Formatter.Format(rootWithTrackedNodes, originalDeclStatementsToMoveOrRemove.Select(s => s.Span), document.Project.Solution.Workspace, cancellationToken: cancellationToken);
document = document.WithSyntaxRoot(rootWithTrackedNodes);
await OnDocumentUpdatedAsync().ConfigureAwait(false);
foreach (TLocalDeclarationStatementSyntax originalDeclStatement in originalDeclStatementsToMoveOrRemove)
{
// Get the current declaration statement.
var declStatement = memberDeclaration.GetCurrentNode(originalDeclStatement);
var documentUpdated = false;
// Check if the variable declaration is unused after all the fixes, and hence can be removed.
if (await TryRemoveUnusedLocalAsync(declStatement, originalDeclStatement).ConfigureAwait(false))
{
documentUpdated = true;
}
else if (declStatement.HasAnnotation(s_newLocalDeclarationStatementAnnotation))
{
// Otherwise, move the declaration closer to the first reference if possible.
if (await service.CanMoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false))
{
document = await service.MoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false);
documentUpdated = true;
}
}
if (documentUpdated)
{
await OnDocumentUpdatedAsync().ConfigureAwait(false);
}
}
return memberDeclaration;
// Local functions.
async Task OnDocumentUpdatedAsync()
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
memberDeclaration = syntaxFacts.GetContainingMemberDeclaration(root, memberDeclaration.SpanStart);
}
async Task<bool> TryRemoveUnusedLocalAsync(TLocalDeclarationStatementSyntax newDecl, TLocalDeclarationStatementSyntax originalDecl)
{
// If we introduced this new local declaration statement while computing the code fix,
// but all it's existing references were removed as part of FixAll, then we
// can remove the unncessary local declaration statement.
// Additionally, if this is an existing local declaration without an initializer,
// such that the local has no references anymore, we can remove it.
if (newDecl.HasAnnotation(s_unusedLocalDeclarationAnnotation) ||
newDecl.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation))
{
// Check if we have no references to local in fixed code.
if (await IsLocalDeclarationWithNoReferencesAsync(newDecl, document, cancellationToken).ConfigureAwait(false))
{
document = document.WithSyntaxRoot(
root.RemoveNode(newDecl, SyntaxGenerator.DefaultRemoveOptions | SyntaxRemoveOptions.KeepLeadingTrivia));
return true;
}
}
return false;
}
}
private static async Task<bool> IsLocalDeclarationWithNoReferencesAsync(
TLocalDeclarationStatementSyntax declStatement,
Document document,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var localDeclarationOperation = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(declStatement, cancellationToken);
var local = localDeclarationOperation.GetDeclaredVariables().Single();
// Check if the declared variable has no references in fixed code.
var referencedSymbols = await SymbolFinder.FindReferencesAsync(local, document.Project.Solution, cancellationToken).ConfigureAwait(false);
return referencedSymbols.Count() == 1 &&
referencedSymbols.Single().Locations.IsEmpty();
}
private sealed class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(title, createChangedDocument, equivalenceKey)
{
}
}
protected sealed class UniqueVariableNameGenerator : IDisposable
{
private readonly SyntaxNode _memberDeclaration;
private readonly SemanticModel _semanticModel;
private readonly ISemanticFactsService _semanticFacts;
private readonly CancellationToken _cancellationToken;
private readonly PooledHashSet<string> _usedNames;
public UniqueVariableNameGenerator(
SyntaxNode memberDeclaration,
SemanticModel semanticModel,
ISemanticFactsService semanticFacts,
CancellationToken cancellationToken)
{
_memberDeclaration = memberDeclaration;
_semanticModel = semanticModel;
_semanticFacts = semanticFacts;
_cancellationToken = cancellationToken;
_usedNames = PooledHashSet<string>.GetInstance();
}
public SyntaxToken GenerateUniqueNameAtSpanStart(SyntaxNode node)
{
var nameToken = _semanticFacts.GenerateUniqueName(_semanticModel, node, _memberDeclaration, "unused", _usedNames, _cancellationToken);
_usedNames.Add(nameToken.ValueText);
return nameToken;
}
public void Dispose() => _usedNames.Free();
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/DocumentSpanEntry.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Editor.QuickInfo;
using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
/// <summary>
/// Entry to show for a particular source location. The row will show the classified
/// contents of that line, and hovering will reveal a tooltip showing that line along
/// with a few lines above/below it.
/// </summary>
private class DocumentSpanEntry : AbstractDocumentSpanEntry, ISupportsNavigation
{
private readonly HighlightSpanKind _spanKind;
private readonly ExcerptResult _excerptResult;
private readonly SymbolReferenceKinds _symbolReferenceKinds;
private readonly ImmutableDictionary<string, string> _customColumnsData;
private readonly string _rawProjectName;
private readonly List<string> _projectFlavors = new();
private string? _cachedProjectName;
private DocumentSpanEntry(
AbstractTableDataSourceFindUsagesContext context,
RoslynDefinitionBucket definitionBucket,
string rawProjectName,
string? projectFlavor,
Guid projectGuid,
HighlightSpanKind spanKind,
MappedSpanResult mappedSpanResult,
ExcerptResult excerptResult,
SourceText lineText,
SymbolUsageInfo symbolUsageInfo,
ImmutableDictionary<string, string> customColumnsData)
: base(context, definitionBucket, projectGuid, lineText, mappedSpanResult)
{
_spanKind = spanKind;
_excerptResult = excerptResult;
_symbolReferenceKinds = symbolUsageInfo.ToSymbolReferenceKinds();
_customColumnsData = customColumnsData;
_rawProjectName = rawProjectName;
this.AddFlavor(projectFlavor);
}
protected override string GetProjectName()
{
// Check if we have any flavors. If we have at least 2, combine with the project name
// so the user can know htat in the UI.
lock (_projectFlavors)
{
if (_cachedProjectName == null)
{
_cachedProjectName = _projectFlavors.Count < 2
? _rawProjectName
: $"{_rawProjectName} ({string.Join(", ", _projectFlavors)})";
}
return _cachedProjectName;
}
}
private void AddFlavor(string? projectFlavor)
{
if (projectFlavor == null)
return;
lock (_projectFlavors)
{
if (_projectFlavors.Contains(projectFlavor))
return;
_projectFlavors.Add(projectFlavor);
_projectFlavors.Sort();
_cachedProjectName = null;
}
}
public static DocumentSpanEntry? TryCreate(
AbstractTableDataSourceFindUsagesContext context,
RoslynDefinitionBucket definitionBucket,
Guid guid,
string projectName,
string? projectFlavor,
string? filePath,
TextSpan sourceSpan,
HighlightSpanKind spanKind,
MappedSpanResult mappedSpanResult,
ExcerptResult excerptResult,
SourceText lineText,
SymbolUsageInfo symbolUsageInfo,
ImmutableDictionary<string, string> customColumnsData)
{
var entry = new DocumentSpanEntry(
context, definitionBucket,
projectName, projectFlavor, guid,
spanKind, mappedSpanResult, excerptResult,
lineText, symbolUsageInfo, customColumnsData);
// Because of things like linked files, we may have a reference up in multiple
// different locations that are effectively at the exact same navigation location
// for the user. i.e. they're the same file/span. Showing multiple entries for these
// is just noisy and gets worse and worse with shared projects and whatnot. So, we
// collapse things down to only show a single entry for each unique file/span pair.
var winningEntry = definitionBucket.GetOrAddEntry(filePath, sourceSpan, entry);
// If we were the one that successfully added this entry to the bucket, then pass us
// back out to be put in the ui.
if (winningEntry == entry)
return entry;
// We were not the winner. Add our flavor to the entry that already exists, but throw
// away the item we created as we do not want to add it to the ui.
winningEntry.AddFlavor(projectFlavor);
return null;
}
protected override IList<System.Windows.Documents.Inline> CreateLineTextInlines()
{
var propertyId = _spanKind == HighlightSpanKind.Definition
? DefinitionHighlightTag.TagId
: _spanKind == HighlightSpanKind.WrittenReference
? WrittenReferenceHighlightTag.TagId
: ReferenceHighlightTag.TagId;
var properties = Presenter.FormatMapService
.GetEditorFormatMap("text")
.GetProperties(propertyId);
// Remove additive classified spans before creating classified text.
// Otherwise the text will be repeated since there are two classifications
// for the same span. Additive classifications should not change the foreground
// color, so the resulting classified text will retain the proper look.
var classifiedSpans = _excerptResult.ClassifiedSpans.WhereAsArray(
cs => !ClassificationTypeNames.AdditiveTypeNames.Contains(cs.ClassificationType));
var classifiedTexts = classifiedSpans.SelectAsArray(
cs => new ClassifiedText(cs.ClassificationType, _excerptResult.Content.ToString(cs.TextSpan)));
var inlines = classifiedTexts.ToInlines(
Presenter.ClassificationFormatMap,
Presenter.TypeMap,
runCallback: (run, classifiedText, position) =>
{
if (properties["Background"] is Brush highlightBrush)
{
if (position == _excerptResult.MappedSpan.Start)
{
run.SetValue(
System.Windows.Documents.TextElement.BackgroundProperty,
highlightBrush);
}
}
});
return inlines;
}
public override bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content)
{
if (base.TryCreateColumnContent(columnName, out content))
{
// this lazy tooltip causes whole solution to be kept in memory until find all reference result gets cleared.
// solution is never supposed to be kept alive for long time, meaning there is bunch of conditional weaktable or weak reference
// keyed by solution/project/document or corresponding states. this will cause all those to be kept alive in memory as well.
// probably we need to dig in to see how expensvie it is to support this
var controlService = _excerptResult.Document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>();
controlService.AttachToolTipToControl(content, () =>
CreateDisposableToolTip(_excerptResult.Document, _excerptResult.Span));
return true;
}
return false;
}
protected override object? GetValueWorker(string keyName)
{
if (keyName == StandardTableKeyNames2.SymbolKind)
{
return _symbolReferenceKinds;
}
if (_customColumnsData.TryGetValue(keyName, out var value))
{
return value;
}
return base.GetValueWorker(keyName);
}
private DisposableToolTip CreateDisposableToolTip(Document document, TextSpan sourceSpan)
{
Presenter.AssertIsForeground();
var controlService = document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>();
var sourceText = document.GetTextSynchronously(CancellationToken.None);
var excerptService = document.Services.GetService<IDocumentExcerptService>();
if (excerptService != null)
{
var excerpt = Presenter.ThreadingContext.JoinableTaskFactory.Run(() => excerptService.TryExcerptAsync(document, sourceSpan, ExcerptMode.Tooltip, CancellationToken.None));
if (excerpt != null)
{
// get tooltip from excerpt service
var clonedBuffer = excerpt.Value.Content.CreateTextBufferWithRoslynContentType(document.Project.Solution.Workspace);
SetHighlightSpan(_spanKind, clonedBuffer, excerpt.Value.MappedSpan);
SetStaticClassifications(clonedBuffer, excerpt.Value.ClassifiedSpans);
return controlService.CreateDisposableToolTip(clonedBuffer, EnvironmentColors.ToolWindowBackgroundBrushKey);
}
}
// get default behavior
var textBuffer = document.CloneTextBuffer(sourceText);
SetHighlightSpan(_spanKind, textBuffer, sourceSpan);
var contentSpan = GetRegionSpanForReference(sourceText, sourceSpan);
return controlService.CreateDisposableToolTip(document, textBuffer, contentSpan, EnvironmentColors.ToolWindowBackgroundBrushKey);
}
private void SetStaticClassifications(ITextBuffer textBuffer, ImmutableArray<ClassifiedSpan> classifiedSpans)
{
var key = PredefinedPreviewTaggerKeys.StaticClassificationSpansKey;
textBuffer.Properties.RemoveProperty(key);
textBuffer.Properties.AddProperty(key, classifiedSpans);
}
private static void SetHighlightSpan(HighlightSpanKind spanKind, ITextBuffer textBuffer, TextSpan span)
{
// Create an appropriate highlight span on that buffer for the reference.
var key = spanKind == HighlightSpanKind.Definition
? PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey
: spanKind == HighlightSpanKind.WrittenReference
? PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey
: PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey;
textBuffer.Properties.RemoveProperty(key);
textBuffer.Properties.AddProperty(key, new NormalizedSnapshotSpanCollection(span.ToSnapshotSpan(textBuffer.CurrentSnapshot)));
}
private static Span GetRegionSpanForReference(SourceText sourceText, TextSpan sourceSpan)
{
const int AdditionalLineCountPerSide = 3;
var referenceSpan = sourceSpan;
var lineNumber = sourceText.Lines.GetLineFromPosition(referenceSpan.Start).LineNumber;
var firstLineNumber = Math.Max(0, lineNumber - AdditionalLineCountPerSide);
var lastLineNumber = Math.Min(sourceText.Lines.Count - 1, lineNumber + AdditionalLineCountPerSide);
return Span.FromBounds(
sourceText.Lines[firstLineNumber].Start,
sourceText.Lines[lastLineNumber].End);
}
async Task<bool> ISupportsNavigation.TryNavigateToAsync(bool isPreview, CancellationToken cancellationToken)
{
// If the document is a source generated document, we need to do the navigation ourselves;
// this is because the file path given to the table control isn't a real file path to a file
// on disk.
if (_excerptResult.Document is SourceGeneratedDocument)
{
var workspace = _excerptResult.Document.Project.Solution.Workspace;
var documentNavigationService = workspace.Services.GetService<IDocumentNavigationService>();
if (documentNavigationService != null)
{
await this.Presenter.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
return documentNavigationService.TryNavigateToSpan(
workspace,
_excerptResult.Document.Id,
_excerptResult.Span,
workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, isPreview),
cancellationToken);
}
}
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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Editor.QuickInfo;
using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
/// <summary>
/// Entry to show for a particular source location. The row will show the classified
/// contents of that line, and hovering will reveal a tooltip showing that line along
/// with a few lines above/below it.
/// </summary>
private sealed class DocumentSpanEntry : AbstractDocumentSpanEntry, ISupportsNavigation
{
private readonly HighlightSpanKind _spanKind;
private readonly ExcerptResult _excerptResult;
private readonly SymbolReferenceKinds _symbolReferenceKinds;
private readonly ImmutableDictionary<string, string> _customColumnsData;
private readonly string _rawProjectName;
private readonly List<string> _projectFlavors = new();
private string? _cachedProjectName;
private DocumentSpanEntry(
AbstractTableDataSourceFindUsagesContext context,
RoslynDefinitionBucket definitionBucket,
string rawProjectName,
string? projectFlavor,
Guid projectGuid,
HighlightSpanKind spanKind,
MappedSpanResult mappedSpanResult,
ExcerptResult excerptResult,
SourceText lineText,
SymbolUsageInfo symbolUsageInfo,
ImmutableDictionary<string, string> customColumnsData)
: base(context, definitionBucket, projectGuid, lineText, mappedSpanResult)
{
_spanKind = spanKind;
_excerptResult = excerptResult;
_symbolReferenceKinds = symbolUsageInfo.ToSymbolReferenceKinds();
_customColumnsData = customColumnsData;
_rawProjectName = rawProjectName;
this.AddFlavor(projectFlavor);
}
protected override string GetProjectName()
{
// Check if we have any flavors. If we have at least 2, combine with the project name
// so the user can know htat in the UI.
lock (_projectFlavors)
{
if (_cachedProjectName == null)
{
_cachedProjectName = _projectFlavors.Count < 2
? _rawProjectName
: $"{_rawProjectName} ({string.Join(", ", _projectFlavors)})";
}
return _cachedProjectName;
}
}
private void AddFlavor(string? projectFlavor)
{
if (projectFlavor == null)
return;
lock (_projectFlavors)
{
if (_projectFlavors.Contains(projectFlavor))
return;
_projectFlavors.Add(projectFlavor);
_projectFlavors.Sort();
_cachedProjectName = null;
}
}
public static DocumentSpanEntry? TryCreate(
AbstractTableDataSourceFindUsagesContext context,
RoslynDefinitionBucket definitionBucket,
Guid guid,
string projectName,
string? projectFlavor,
string? filePath,
TextSpan sourceSpan,
HighlightSpanKind spanKind,
MappedSpanResult mappedSpanResult,
ExcerptResult excerptResult,
SourceText lineText,
SymbolUsageInfo symbolUsageInfo,
ImmutableDictionary<string, string> customColumnsData)
{
var entry = new DocumentSpanEntry(
context, definitionBucket,
projectName, projectFlavor, guid,
spanKind, mappedSpanResult, excerptResult,
lineText, symbolUsageInfo, customColumnsData);
// Because of things like linked files, we may have a reference up in multiple
// different locations that are effectively at the exact same navigation location
// for the user. i.e. they're the same file/span. Showing multiple entries for these
// is just noisy and gets worse and worse with shared projects and whatnot. So, we
// collapse things down to only show a single entry for each unique file/span pair.
var winningEntry = definitionBucket.GetOrAddEntry(filePath, sourceSpan, entry);
// If we were the one that successfully added this entry to the bucket, then pass us
// back out to be put in the ui.
if (winningEntry == entry)
return entry;
// We were not the winner. Add our flavor to the entry that already exists, but throw
// away the item we created as we do not want to add it to the ui.
winningEntry.AddFlavor(projectFlavor);
return null;
}
protected override IList<System.Windows.Documents.Inline> CreateLineTextInlines()
{
var propertyId = _spanKind == HighlightSpanKind.Definition
? DefinitionHighlightTag.TagId
: _spanKind == HighlightSpanKind.WrittenReference
? WrittenReferenceHighlightTag.TagId
: ReferenceHighlightTag.TagId;
var properties = Presenter.FormatMapService
.GetEditorFormatMap("text")
.GetProperties(propertyId);
// Remove additive classified spans before creating classified text.
// Otherwise the text will be repeated since there are two classifications
// for the same span. Additive classifications should not change the foreground
// color, so the resulting classified text will retain the proper look.
var classifiedSpans = _excerptResult.ClassifiedSpans.WhereAsArray(
cs => !ClassificationTypeNames.AdditiveTypeNames.Contains(cs.ClassificationType));
var classifiedTexts = classifiedSpans.SelectAsArray(
cs => new ClassifiedText(cs.ClassificationType, _excerptResult.Content.ToString(cs.TextSpan)));
var inlines = classifiedTexts.ToInlines(
Presenter.ClassificationFormatMap,
Presenter.TypeMap,
runCallback: (run, classifiedText, position) =>
{
if (properties["Background"] is Brush highlightBrush)
{
if (position == _excerptResult.MappedSpan.Start)
{
run.SetValue(
System.Windows.Documents.TextElement.BackgroundProperty,
highlightBrush);
}
}
});
return inlines;
}
public override bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content)
{
if (base.TryCreateColumnContent(columnName, out content))
{
// this lazy tooltip causes whole solution to be kept in memory until find all reference result gets cleared.
// solution is never supposed to be kept alive for long time, meaning there is bunch of conditional weaktable or weak reference
// keyed by solution/project/document or corresponding states. this will cause all those to be kept alive in memory as well.
// probably we need to dig in to see how expensvie it is to support this
var controlService = _excerptResult.Document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>();
controlService.AttachToolTipToControl(content, () =>
CreateDisposableToolTip(_excerptResult.Document, _excerptResult.Span));
return true;
}
return false;
}
protected override object? GetValueWorker(string keyName)
{
if (keyName == StandardTableKeyNames2.SymbolKind)
{
return _symbolReferenceKinds;
}
if (_customColumnsData.TryGetValue(keyName, out var value))
{
return value;
}
return base.GetValueWorker(keyName);
}
private DisposableToolTip CreateDisposableToolTip(Document document, TextSpan sourceSpan)
{
Presenter.AssertIsForeground();
var controlService = document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>();
var sourceText = document.GetTextSynchronously(CancellationToken.None);
var excerptService = document.Services.GetService<IDocumentExcerptService>();
if (excerptService != null)
{
var excerpt = Presenter.ThreadingContext.JoinableTaskFactory.Run(() => excerptService.TryExcerptAsync(document, sourceSpan, ExcerptMode.Tooltip, CancellationToken.None));
if (excerpt != null)
{
// get tooltip from excerpt service
var clonedBuffer = excerpt.Value.Content.CreateTextBufferWithRoslynContentType(document.Project.Solution.Workspace);
SetHighlightSpan(_spanKind, clonedBuffer, excerpt.Value.MappedSpan);
SetStaticClassifications(clonedBuffer, excerpt.Value.ClassifiedSpans);
return controlService.CreateDisposableToolTip(clonedBuffer, EnvironmentColors.ToolWindowBackgroundBrushKey);
}
}
// get default behavior
var textBuffer = document.CloneTextBuffer(sourceText);
SetHighlightSpan(_spanKind, textBuffer, sourceSpan);
var contentSpan = GetRegionSpanForReference(sourceText, sourceSpan);
return controlService.CreateDisposableToolTip(document, textBuffer, contentSpan, EnvironmentColors.ToolWindowBackgroundBrushKey);
}
private void SetStaticClassifications(ITextBuffer textBuffer, ImmutableArray<ClassifiedSpan> classifiedSpans)
{
var key = PredefinedPreviewTaggerKeys.StaticClassificationSpansKey;
textBuffer.Properties.RemoveProperty(key);
textBuffer.Properties.AddProperty(key, classifiedSpans);
}
private static void SetHighlightSpan(HighlightSpanKind spanKind, ITextBuffer textBuffer, TextSpan span)
{
// Create an appropriate highlight span on that buffer for the reference.
var key = spanKind == HighlightSpanKind.Definition
? PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey
: spanKind == HighlightSpanKind.WrittenReference
? PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey
: PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey;
textBuffer.Properties.RemoveProperty(key);
textBuffer.Properties.AddProperty(key, new NormalizedSnapshotSpanCollection(span.ToSnapshotSpan(textBuffer.CurrentSnapshot)));
}
private static Span GetRegionSpanForReference(SourceText sourceText, TextSpan sourceSpan)
{
const int AdditionalLineCountPerSide = 3;
var referenceSpan = sourceSpan;
var lineNumber = sourceText.Lines.GetLineFromPosition(referenceSpan.Start).LineNumber;
var firstLineNumber = Math.Max(0, lineNumber - AdditionalLineCountPerSide);
var lastLineNumber = Math.Min(sourceText.Lines.Count - 1, lineNumber + AdditionalLineCountPerSide);
return Span.FromBounds(
sourceText.Lines[firstLineNumber].Start,
sourceText.Lines[lastLineNumber].End);
}
public bool CanNavigateTo()
{
if (_excerptResult.Document is SourceGeneratedDocument)
{
var workspace = _excerptResult.Document.Project.Solution.Workspace;
var documentNavigationService = workspace.Services.GetService<IDocumentNavigationService>();
return documentNavigationService != null;
}
return false;
}
public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(CanNavigateTo());
// If the document is a source generated document, we need to do the navigation ourselves;
// this is because the file path given to the table control isn't a real file path to a file
// on disk.
var workspace = _excerptResult.Document.Project.Solution.Workspace;
var documentNavigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>();
return documentNavigationService.TryNavigateToSpanAsync(
workspace,
_excerptResult.Document.Id,
_excerptResult.Span,
workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, isPreview),
cancellationToken);
}
}
}
}
| 1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/Entry.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.VisualStudio.Shell.TableControl;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
/// <summary>
/// Represents a single entry (i.e. row) in the ungrouped FAR table.
/// </summary>
private abstract class Entry
{
public readonly RoslynDefinitionBucket DefinitionBucket;
protected Entry(RoslynDefinitionBucket definitionBucket)
=> DefinitionBucket = definitionBucket;
public bool TryGetValue(string keyName, out object? content)
{
content = GetValue(keyName);
return content != null;
}
private object? GetValue(string keyName)
{
switch (keyName)
{
case StandardTableKeyNames2.Definition:
return DefinitionBucket;
case StandardTableKeyNames2.DefinitionIcon:
return DefinitionBucket?.DefinitionItem.Tags.GetFirstGlyph().GetImageMoniker();
}
return GetValueWorker(keyName);
}
protected abstract object? GetValueWorker(string keyName);
public virtual bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content)
{
content = null;
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.VisualStudio.Shell.TableControl;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
/// <summary>
/// Represents a single entry (i.e. row) in the ungrouped FAR table.
/// </summary>
private abstract class Entry
{
public readonly RoslynDefinitionBucket DefinitionBucket;
protected Entry(RoslynDefinitionBucket definitionBucket)
=> DefinitionBucket = definitionBucket;
public bool TryGetValue(string keyName, out object? content)
{
content = GetValue(keyName);
return content != null;
}
private object? GetValue(string keyName)
{
switch (keyName)
{
case StandardTableKeyNames2.Definition:
return DefinitionBucket;
case StandardTableKeyNames2.DefinitionIcon:
return DefinitionBucket?.DefinitionItem.Tags.GetFirstGlyph().GetImageMoniker();
}
return GetValueWorker(keyName);
}
protected abstract object? GetValueWorker(string keyName);
public virtual bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content)
{
content = null;
return false;
}
}
}
}
| 1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/MetadataDefinitionItemEntry.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Documents;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
private class MetadataDefinitionItemEntry : AbstractItemEntry, ISupportsNavigation
{
public MetadataDefinitionItemEntry(
AbstractTableDataSourceFindUsagesContext context,
RoslynDefinitionBucket definitionBucket)
: base(definitionBucket, context.Presenter)
{
}
protected override object? GetValueWorker(string keyName)
{
switch (keyName)
{
case StandardTableKeyNames.Text:
return DefinitionBucket.DefinitionItem.DisplayParts.JoinText();
}
return null;
}
Task<bool> ISupportsNavigation.TryNavigateToAsync(bool isPreview, CancellationToken cancellationToken)
=> DefinitionBucket.DefinitionItem.TryNavigateToAsync(
Presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview
protected override IList<Inline> CreateLineTextInlines()
=> DefinitionBucket.DefinitionItem.DisplayParts
.ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Documents;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
private class MetadataDefinitionItemEntry : AbstractItemEntry, ISupportsNavigation
{
public MetadataDefinitionItemEntry(
AbstractTableDataSourceFindUsagesContext context,
RoslynDefinitionBucket definitionBucket)
: base(definitionBucket, context.Presenter)
{
}
protected override object? GetValueWorker(string keyName)
{
switch (keyName)
{
case StandardTableKeyNames.Text:
return DefinitionBucket.DefinitionItem.DisplayParts.JoinText();
}
return null;
}
public bool CanNavigateTo()
=> true;
public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken)
=> DefinitionBucket.DefinitionItem.TryNavigateToAsync(
Presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview
protected override IList<Inline> CreateLineTextInlines()
=> DefinitionBucket.DefinitionItem.DisplayParts
.ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap);
}
}
}
| 1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/SimpleMessageEntry.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
private class SimpleMessageEntry : Entry, ISupportsNavigation
{
private readonly RoslynDefinitionBucket? _navigationBucket;
private readonly string _message;
private SimpleMessageEntry(
RoslynDefinitionBucket definitionBucket,
RoslynDefinitionBucket? navigationBucket,
string message)
: base(definitionBucket)
{
_navigationBucket = navigationBucket;
_message = message;
}
public static Task<Entry> CreateAsync(
RoslynDefinitionBucket definitionBucket,
RoslynDefinitionBucket? navigationBucket,
string message)
{
var referenceEntry = new SimpleMessageEntry(definitionBucket, navigationBucket, message);
return Task.FromResult<Entry>(referenceEntry);
}
protected override object? GetValueWorker(string keyName)
{
return keyName switch
{
StandardTableKeyNames.ProjectName => "Not applicable",
StandardTableKeyNames.Text => _message,
_ => null,
};
}
public async Task<bool> TryNavigateToAsync(bool isPreview, CancellationToken cancellationToken)
=> _navigationBucket != null && await _navigationBucket.TryNavigateToAsync(isPreview, cancellationToken).ConfigureAwait(false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.TableManager;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
private sealed class SimpleMessageEntry : Entry, ISupportsNavigation
{
private readonly RoslynDefinitionBucket? _navigationBucket;
private readonly string _message;
private SimpleMessageEntry(
RoslynDefinitionBucket definitionBucket,
RoslynDefinitionBucket? navigationBucket,
string message)
: base(definitionBucket)
{
_navigationBucket = navigationBucket;
_message = message;
}
public static Task<Entry> CreateAsync(
RoslynDefinitionBucket definitionBucket,
RoslynDefinitionBucket? navigationBucket,
string message)
{
var referenceEntry = new SimpleMessageEntry(definitionBucket, navigationBucket, message);
return Task.FromResult<Entry>(referenceEntry);
}
protected override object? GetValueWorker(string keyName)
{
return keyName switch
{
StandardTableKeyNames.ProjectName => "Not applicable",
StandardTableKeyNames.Text => _message,
_ => null,
};
}
public bool CanNavigateTo()
=> _navigationBucket != null && _navigationBucket.CanNavigateTo();
public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(CanNavigateTo());
Contract.ThrowIfNull(_navigationBucket);
return _navigationBucket.NavigateToAsync(isPreview, cancellationToken);
}
}
}
}
| 1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/FindReferences/FindReferencesTableControlEventProcessorProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.Utilities;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Text.Classification;
using System;
using Microsoft.CodeAnalysis.Host.Mef;
using System.Threading;
using Microsoft.CodeAnalysis.Editor;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
/// <summary>
/// Event processor that we export so we can control how navigation works in the streaming
/// FAR window. We need this because the FAR window has no way to know how to do things like
/// navigate to definitions that are from metadata. We take control here and handle navigation
/// ourselves so that we can do things like navigate to MetadataAsSource.
/// </summary>
[Export(typeof(ITableControlEventProcessorProvider))]
[DataSourceType(StreamingFindUsagesPresenter.RoslynFindUsagesTableDataSourceSourceTypeIdentifier)]
[DataSource(StreamingFindUsagesPresenter.RoslynFindUsagesTableDataSourceIdentifier)]
[Name(nameof(FindUsagesTableControlEventProcessorProvider))]
[Order(Before = Priority.Default)]
internal class FindUsagesTableControlEventProcessorProvider : ITableControlEventProcessorProvider
{
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FindUsagesTableControlEventProcessorProvider(
IUIThreadOperationExecutor operationExecutor,
IAsynchronousOperationListenerProvider asyncProvider)
{
_operationExecutor = operationExecutor;
_listener = asyncProvider.GetListener(FeatureAttribute.FindReferences);
}
public ITableControlEventProcessor GetAssociatedEventProcessor(IWpfTableControl tableControl)
=> new TableControlEventProcessor(_operationExecutor, _listener);
private class TableControlEventProcessor : TableControlEventProcessorBase
{
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly IAsynchronousOperationListener _listener;
public TableControlEventProcessor(IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListener listener)
{
_operationExecutor = operationExecutor;
_listener = listener;
}
public override void PreprocessNavigate(ITableEntryHandle entry, TableEntryNavigateEventArgs e)
{
var supportsNavigation = entry.Identity as ISupportsNavigation ??
(entry.TryGetValue(StreamingFindUsagesPresenter.SelfKeyName, out var item) ? item as ISupportsNavigation : null);
if (supportsNavigation == null)
{
base.PreprocessNavigate(entry, e);
return;
}
// Fire and forget
e.Handled = true;
_ = ProcessNavigateAsync(supportsNavigation, e, _listener, _operationExecutor);
return;
async static Task ProcessNavigateAsync(
ISupportsNavigation supportsNavigation, TableEntryNavigateEventArgs e,
IAsynchronousOperationListener listener,
IUIThreadOperationExecutor operationExecutor)
{
using var token = listener.BeginAsyncOperation(nameof(ProcessNavigateAsync));
using var context = operationExecutor.BeginExecute(
ServicesVSResources.IntelliSense,
EditorFeaturesResources.Navigating,
allowCancellation: true,
showProgress: false);
await supportsNavigation.TryNavigateToAsync(e.IsPreview, context.UserCancellationToken).ConfigureAwait(false);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.Utilities;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Text.Classification;
using System;
using Microsoft.CodeAnalysis.Host.Mef;
using System.Threading;
using Microsoft.CodeAnalysis.Editor;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
/// <summary>
/// Event processor that we export so we can control how navigation works in the streaming
/// FAR window. We need this because the FAR window has no way to know how to do things like
/// navigate to definitions that are from metadata. We take control here and handle navigation
/// ourselves so that we can do things like navigate to MetadataAsSource.
/// </summary>
[Export(typeof(ITableControlEventProcessorProvider))]
[DataSourceType(StreamingFindUsagesPresenter.RoslynFindUsagesTableDataSourceSourceTypeIdentifier)]
[DataSource(StreamingFindUsagesPresenter.RoslynFindUsagesTableDataSourceIdentifier)]
[Name(nameof(FindUsagesTableControlEventProcessorProvider))]
[Order(Before = Priority.Default)]
internal class FindUsagesTableControlEventProcessorProvider : ITableControlEventProcessorProvider
{
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FindUsagesTableControlEventProcessorProvider(
IUIThreadOperationExecutor operationExecutor,
IAsynchronousOperationListenerProvider asyncProvider)
{
_operationExecutor = operationExecutor;
_listener = asyncProvider.GetListener(FeatureAttribute.FindReferences);
}
public ITableControlEventProcessor GetAssociatedEventProcessor(IWpfTableControl tableControl)
=> new TableControlEventProcessor(_operationExecutor, _listener);
private class TableControlEventProcessor : TableControlEventProcessorBase
{
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly IAsynchronousOperationListener _listener;
public TableControlEventProcessor(IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListener listener)
{
_operationExecutor = operationExecutor;
_listener = listener;
}
public override void PreprocessNavigate(ITableEntryHandle entry, TableEntryNavigateEventArgs e)
{
var supportsNavigation = entry.Identity as ISupportsNavigation ??
(entry.TryGetValue(StreamingFindUsagesPresenter.SelfKeyName, out var item) ? item as ISupportsNavigation : null);
if (supportsNavigation != null &&
supportsNavigation.CanNavigateTo())
{
// Fire and forget
e.Handled = true;
_ = ProcessNavigateAsync(supportsNavigation, e, _listener, _operationExecutor);
}
base.PreprocessNavigate(entry, e);
return;
async static Task ProcessNavigateAsync(
ISupportsNavigation supportsNavigation, TableEntryNavigateEventArgs e,
IAsynchronousOperationListener listener,
IUIThreadOperationExecutor operationExecutor)
{
using var token = listener.BeginAsyncOperation(nameof(ProcessNavigateAsync));
using var context = operationExecutor.BeginExecute(
ServicesVSResources.IntelliSense,
EditorFeaturesResources.Navigating,
allowCancellation: true,
showProgress: false);
await supportsNavigation.NavigateToAsync(e.IsPreview, context.UserCancellationToken).ConfigureAwait(false);
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/FindReferences/ISupportsNavigation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal interface ISupportsNavigation
{
Task<bool> TryNavigateToAsync(bool isPreview, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal interface ISupportsNavigation
{
bool CanNavigateTo();
Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken);
}
}
| 1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/FindReferences/RoslynDefinitionBucket.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.FindAllReferences;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
private class RoslynDefinitionBucket : DefinitionBucket, ISupportsNavigation
{
private readonly StreamingFindUsagesPresenter _presenter;
public readonly DefinitionItem DefinitionItem;
/// <summary>
/// Due to linked files, we may have results for several locations that are all effectively
/// the same file/span. So we represent this as one entry with several project flavors. If
/// we get more than one flavor, we'll show that the user in the UI.
/// </summary>
private readonly Dictionary<(string? filePath, TextSpan span), DocumentSpanEntry> _locationToEntry = new();
public RoslynDefinitionBucket(
string name,
bool expandedByDefault,
StreamingFindUsagesPresenter presenter,
AbstractTableDataSourceFindUsagesContext context,
DefinitionItem definitionItem)
: base(name,
sourceTypeIdentifier: context.SourceTypeIdentifier,
identifier: context.Identifier,
expandedByDefault: expandedByDefault)
{
_presenter = presenter;
DefinitionItem = definitionItem;
}
public static RoslynDefinitionBucket Create(
StreamingFindUsagesPresenter presenter,
AbstractTableDataSourceFindUsagesContext context,
DefinitionItem definitionItem,
bool expandedByDefault)
{
var isPrimary = definitionItem.Properties.ContainsKey(DefinitionItem.Primary);
// Sort the primary item above everything else.
var name = $"{(isPrimary ? 0 : 1)} {definitionItem.DisplayParts.JoinText()} {definitionItem.GetHashCode()}";
return new RoslynDefinitionBucket(
name, expandedByDefault, presenter, context, definitionItem);
}
public Task<bool> TryNavigateToAsync(bool isPreview, CancellationToken cancellationToken)
=> DefinitionItem.TryNavigateToAsync(
_presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview
public override bool TryGetValue(string key, out object? content)
{
content = GetValue(key);
return content != null;
}
/// <summary>
/// The editor is presenting 'Text' while telling the screen reader to use the 'Name' field.
/// Workaround this bug by overriding the string content to provide the proper data for the screen reader.
/// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1020534/
/// </summary>
public override bool TryCreateStringContent(out string? content)
{
if (TryGetValue(StandardTableKeyNames.Text, out var contentValue) && contentValue is string textContent)
{
content = textContent;
return true;
}
content = null;
return false;
}
private object? GetValue(string key)
{
switch (key)
{
case StandardTableKeyNames.Text:
case StandardTableKeyNames.FullText:
return DefinitionItem.DisplayParts.JoinText();
case StandardTableKeyNames2.TextInlines:
var inlines = new List<Inline> { new Run(" ") };
inlines.AddRange(DefinitionItem.DisplayParts.ToInlines(_presenter.ClassificationFormatMap, _presenter.TypeMap));
foreach (var inline in inlines)
{
inline.SetValue(TextElement.FontWeightProperty, FontWeights.Bold);
}
return inlines;
case StandardTableKeyNames2.DefinitionIcon:
return DefinitionItem.Tags.GetFirstGlyph().GetImageMoniker();
}
return null;
}
public DocumentSpanEntry GetOrAddEntry(string? filePath, TextSpan sourceSpan, DocumentSpanEntry entry)
{
var key = (filePath, sourceSpan);
lock (_locationToEntry)
{
return _locationToEntry.GetOrAdd(key, entry);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.FindAllReferences;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
internal partial class StreamingFindUsagesPresenter
{
private class RoslynDefinitionBucket : DefinitionBucket, ISupportsNavigation
{
private readonly StreamingFindUsagesPresenter _presenter;
public readonly DefinitionItem DefinitionItem;
/// <summary>
/// Due to linked files, we may have results for several locations that are all effectively
/// the same file/span. So we represent this as one entry with several project flavors. If
/// we get more than one flavor, we'll show that the user in the UI.
/// </summary>
private readonly Dictionary<(string? filePath, TextSpan span), DocumentSpanEntry> _locationToEntry = new();
public RoslynDefinitionBucket(
string name,
bool expandedByDefault,
StreamingFindUsagesPresenter presenter,
AbstractTableDataSourceFindUsagesContext context,
DefinitionItem definitionItem)
: base(name,
sourceTypeIdentifier: context.SourceTypeIdentifier,
identifier: context.Identifier,
expandedByDefault: expandedByDefault)
{
_presenter = presenter;
DefinitionItem = definitionItem;
}
public static RoslynDefinitionBucket Create(
StreamingFindUsagesPresenter presenter,
AbstractTableDataSourceFindUsagesContext context,
DefinitionItem definitionItem,
bool expandedByDefault)
{
var isPrimary = definitionItem.Properties.ContainsKey(DefinitionItem.Primary);
// Sort the primary item above everything else.
var name = $"{(isPrimary ? 0 : 1)} {definitionItem.DisplayParts.JoinText()} {definitionItem.GetHashCode()}";
return new RoslynDefinitionBucket(
name, expandedByDefault, presenter, context, definitionItem);
}
public bool CanNavigateTo()
=> true;
public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken)
=> DefinitionItem.TryNavigateToAsync(
_presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview
public override bool TryGetValue(string key, out object? content)
{
content = GetValue(key);
return content != null;
}
/// <summary>
/// The editor is presenting 'Text' while telling the screen reader to use the 'Name' field.
/// Workaround this bug by overriding the string content to provide the proper data for the screen reader.
/// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1020534/
/// </summary>
public override bool TryCreateStringContent(out string? content)
{
if (TryGetValue(StandardTableKeyNames.Text, out var contentValue) && contentValue is string textContent)
{
content = textContent;
return true;
}
content = null;
return false;
}
private object? GetValue(string key)
{
switch (key)
{
case StandardTableKeyNames.Text:
case StandardTableKeyNames.FullText:
return DefinitionItem.DisplayParts.JoinText();
case StandardTableKeyNames2.TextInlines:
var inlines = new List<Inline> { new Run(" ") };
inlines.AddRange(DefinitionItem.DisplayParts.ToInlines(_presenter.ClassificationFormatMap, _presenter.TypeMap));
foreach (var inline in inlines)
{
inline.SetValue(TextElement.FontWeightProperty, FontWeights.Bold);
}
return inlines;
case StandardTableKeyNames2.DefinitionIcon:
return DefinitionItem.Tags.GetFirstGlyph().GetImageMoniker();
}
return null;
}
public DocumentSpanEntry GetOrAddEntry(string? filePath, TextSpan sourceSpan, DocumentSpanEntry entry)
{
var key = (filePath, sourceSpan);
lock (_locationToEntry)
{
return _locationToEntry.GetOrAdd(key, entry);
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStorage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// TemporaryStorage can be used to read and write text to a temporary storage location.
/// </summary>
public interface ITemporaryTextStorage : IDisposable
{
SourceText ReadText(CancellationToken cancellationToken = default);
Task<SourceText> ReadTextAsync(CancellationToken cancellationToken = default);
void WriteText(SourceText text, CancellationToken cancellationToken = default);
Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default);
}
public interface ITemporaryStreamStorage : IDisposable
{
Stream ReadStream(CancellationToken cancellationToken = default);
Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default);
void WriteStream(Stream stream, CancellationToken cancellationToken = default);
Task WriteStreamAsync(Stream stream, 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;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// TemporaryStorage can be used to read and write text to a temporary storage location.
/// </summary>
public interface ITemporaryTextStorage : IDisposable
{
SourceText ReadText(CancellationToken cancellationToken = default);
Task<SourceText> ReadTextAsync(CancellationToken cancellationToken = default);
void WriteText(SourceText text, CancellationToken cancellationToken = default);
Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default);
}
public interface ITemporaryStreamStorage : IDisposable
{
Stream ReadStream(CancellationToken cancellationToken = default);
Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default);
void WriteStream(Stream stream, CancellationToken cancellationToken = default);
Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/CSharp/Impl/CodeModel/Extenders/ExtensionMethodExtender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICSExtensionMethodExtender))]
public class ExtensionMethodExtender : ICSExtensionMethodExtender
{
internal static ICSExtensionMethodExtender Create(bool isExtension)
{
var result = new ExtensionMethodExtender(isExtension);
return (ICSExtensionMethodExtender)ComAggregate.CreateAggregatedObject(result);
}
private readonly bool _isExtension;
private ExtensionMethodExtender(bool isExtension)
=> _isExtension = isExtension;
public bool IsExtension
{
get { return _isExtension; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICSExtensionMethodExtender))]
public class ExtensionMethodExtender : ICSExtensionMethodExtender
{
internal static ICSExtensionMethodExtender Create(bool isExtension)
{
var result = new ExtensionMethodExtender(isExtension);
return (ICSExtensionMethodExtender)ComAggregate.CreateAggregatedObject(result);
}
private readonly bool _isExtension;
private ExtensionMethodExtender(bool isExtension)
=> _isExtension = isExtension;
public bool IsExtension
{
get { return _isExtension; }
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/AdditionalText.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a non source code file.
/// </summary>
public abstract class AdditionalText
{
/// <summary>
/// Path to the text.
/// </summary>
public abstract string Path { get; }
/// <summary>
/// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if
/// there were errors reading the file.
/// </summary>
public abstract SourceText? GetText(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.
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a non source code file.
/// </summary>
public abstract class AdditionalText
{
/// <summary>
/// Path to the text.
/// </summary>
public abstract string Path { get; }
/// <summary>
/// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if
/// there were errors reading the file.
/// </summary>
public abstract SourceText? GetText(CancellationToken cancellationToken = default);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/Editor_OutOfProc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Windows;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using UIAutomationClient;
using Xunit;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
/// <summary>
/// Provides a means of interacting with the Visual Studio editor by remoting calls into Visual Studio.
/// </summary>
public partial class Editor_OutOfProc : TextViewWindow_OutOfProc
{
public new Verifier Verify { get; }
private readonly Editor_InProc _editorInProc;
private readonly VisualStudioInstance _instance;
internal Editor_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
_instance = visualStudioInstance;
_editorInProc = (Editor_InProc)_textViewWindowInProc;
Verify = new Verifier(this, _instance);
}
internal override TextViewWindow_InProc CreateInProcComponent(VisualStudioInstance visualStudioInstance)
=> CreateInProcComponent<Editor_InProc>(visualStudioInstance);
public void Activate()
=> _editorInProc.Activate();
public string GetText()
=> _editorInProc.GetText();
public void SetText(string value)
=> _editorInProc.SetText(value);
public string GetCurrentLineText()
=> _editorInProc.GetCurrentLineText();
public string GetLineTextBeforeCaret()
=> _editorInProc.GetLineTextBeforeCaret();
public string GetSelectedText()
=> _editorInProc.GetSelectedText();
public string GetLineTextAfterCaret()
=> _editorInProc.GetLineTextAfterCaret();
public void MoveCaret(int position)
=> _editorInProc.MoveCaret(position);
public ImmutableArray<TextSpan> GetTagSpans(string tagId)
{
if (tagId == _instance.InlineRenameDialog.ValidRenameTag)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Rename);
}
var tagInfo = _editorInProc.GetTagSpans(tagId).ToList();
// The spans are returned in an array:
// [s1.Start, s1.Length, s2.Start, s2.Length, ...]
// Reconstruct the spans from their component parts
var builder = ArrayBuilder<TextSpan>.GetInstance();
for (var i = 0; i < tagInfo.Count; i += 2)
{
builder.Add(new TextSpan(tagInfo[i], tagInfo[i + 1]));
}
return builder.ToImmutableAndFree();
}
public void InvokeNavigateToNextHighlightedReference()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
_instance.ExecuteCommand(WellKnownCommandNames.Edit_NextHighlightedReference);
}
public string GetCurrentCompletionItem()
{
WaitForCompletionSet();
return _editorInProc.GetCurrentCompletionItem();
}
public bool IsCompletionActive()
{
WaitForCompletionSet();
return _editorInProc.IsCompletionActive();
}
public void InvokeSignatureHelp()
{
_instance.ExecuteCommand(WellKnownCommandNames.Edit_ParameterInfo);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
}
public bool IsSignatureHelpActive()
{
WaitForSignatureHelp();
return _editorInProc.IsSignatureHelpActive();
}
public Signature[] GetSignatures()
{
WaitForSignatureHelp();
return _editorInProc.GetSignatures();
}
public Signature GetCurrentSignature()
{
WaitForSignatureHelp();
return _editorInProc.GetCurrentSignature();
}
public void InvokeNavigateTo(params object[] keys)
{
_instance.ExecuteCommand(WellKnownCommandNames.Edit_GoToAll);
NavigateToSendKeys(keys);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigateTo);
}
public void SelectTextInCurrentDocument(string text)
{
PlaceCaret(text, charsOffset: -1, occurrence: 0, extendSelection: false, selectBlock: false);
PlaceCaret(text, charsOffset: 0, occurrence: 0, extendSelection: true, selectBlock: false);
}
public int GetLine() => _editorInProc.GetLine();
public int GetColumn() => _editorInProc.GetColumn();
public void DeleteText(string text)
{
SelectTextInCurrentDocument(text);
SendKeys(VirtualKey.Delete);
}
public void ReplaceText(string oldText, string newText)
=> _editorInProc.ReplaceText(oldText, newText);
public bool IsCaretOnScreen()
=> _editorInProc.IsCaretOnScreen();
public void AddWinFormButton(string buttonName)
=> _editorInProc.AddWinFormButton(buttonName);
public void DeleteWinFormButton(string buttonName)
=> _editorInProc.DeleteWinFormButton(buttonName);
public void EditWinFormButtonProperty(string buttonName, string propertyName, string propertyValue, string? propertyTypeName = null)
=> _editorInProc.EditWinFormButtonProperty(buttonName, propertyName, propertyValue, propertyTypeName);
public void EditWinFormButtonEvent(string buttonName, string eventName, string eventHandlerName)
=> _editorInProc.EditWinFormButtonEvent(buttonName, eventName, eventHandlerName);
public string? GetWinFormButtonPropertyValue(string buttonName, string propertyName)
=> _editorInProc.GetWinFormButtonPropertyValue(buttonName, propertyName);
/// <summary>
/// Sends key strokes to the active editor in Visual Studio. Various types are supported by this method:
/// <see cref="string"/> (each character will be sent separately, <see cref="char"/>, <see cref="VirtualKey"/>
/// and <see cref="KeyPress"/>.
/// </summary>
public void SendKeys(params object[] keys)
{
Activate();
VisualStudioInstance.SendKeys.Send(keys);
}
public void MessageBox(string message)
=> _editorInProc.MessageBox(message);
public IUIAutomationElement GetDialog(string dialogAutomationId)
{
var dialog = DialogHelpers.GetOpenDialogById(_instance.Shell.GetHWnd(), dialogAutomationId);
return dialog;
}
public void VerifyDialog(string dialogName, bool isOpen)
=> _editorInProc.VerifyDialog(dialogName, isOpen);
public void PressDialogButton(string dialogAutomationName, string buttonAutomationName)
=> _editorInProc.PressDialogButton(dialogAutomationName, buttonAutomationName);
public void DialogSendKeys(string dialogAutomationName, params object[] keys)
=> _editorInProc.DialogSendKeys(dialogAutomationName, keys);
public void FormatDocument()
{
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
SendKeys(new KeyPress(VirtualKey.K, ShiftState.Ctrl), new KeyPress(VirtualKey.D, ShiftState.Ctrl));
}
public void FormatDocumentViaCommand()
{
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
_editorInProc.FormatDocumentViaCommand();
}
public void FormatSelection()
{
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
SendKeys(new KeyPress(VirtualKey.K, ShiftState.Ctrl), new KeyPress(VirtualKey.F, ShiftState.Ctrl));
}
public void Paste(string text)
{
var thread = new Thread(() => Clipboard.SetText(text));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
_editorInProc.Paste();
}
public void Undo()
=> _editorInProc.Undo();
public void Redo()
=> _editorInProc.Redo();
public void NavigateToSendKeys(params object[] keys)
=> _editorInProc.SendKeysToNavigateTo(keys);
public ClassifiedToken[] GetLightbulbPreviewClassification(string menuText) =>
_editorInProc.GetLightbulbPreviewClassifications(menuText);
public bool IsUseSuggestionModeOn()
=> _editorInProc.IsUseSuggestionModeOn();
public void SetUseSuggestionMode(bool value)
{
Assert.False(IsCompletionActive());
_editorInProc.SetUseSuggestionMode(value);
}
public void WaitForActiveView(string viewName)
=> _editorInProc.WaitForActiveView(viewName);
public void WaitForActiveWindow(string windowName)
=> _editorInProc.WaitForActiveWindow(windowName);
public string[] GetErrorTags()
=> _editorInProc.GetErrorTags();
public List<string> GetF1Keyword()
=> _editorInProc.GetF1Keywords();
public void ExpandProjectNavBar()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.ExpandNavigationBar(0);
}
public void ExpandTypeNavBar()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.ExpandNavigationBar(1);
}
public void ExpandMemberNavBar()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.ExpandNavigationBar(2);
}
public string[] GetProjectNavBarItems()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetNavBarItems(0);
}
public string[] GetTypeNavBarItems()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetNavBarItems(1);
}
public string[] GetMemberNavBarItems()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetNavBarItems(2);
}
public string? GetProjectNavBarSelection()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetSelectedNavBarItem(0);
}
public string? GetTypeNavBarSelection()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetSelectedNavBarItem(1);
}
public string? GetMemberNavBarSelection()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetSelectedNavBarItem(2);
}
public void SelectProjectNavbarItem(string item)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.SelectNavBarItem(0, item);
}
public void SelectTypeNavBarItem(string item)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.SelectNavBarItem(1, item);
}
public void SelectMemberNavBarItem(string item)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.SelectNavBarItem(2, item);
}
public bool IsNavBarEnabled()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.IsNavBarEnabled();
}
public TextSpan[] GetKeywordHighlightTags()
=> Deserialize(_editorInProc.GetHighlightTags());
public TextSpan[] GetOutliningSpans()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Outlining);
return Deserialize(_editorInProc.GetOutliningSpans());
}
private TextSpan[] Deserialize(string[] v)
{
// returned tag looks something like 'text'[12-13]
return v.Select(tag =>
{
var open = tag.LastIndexOf('[') + 1;
var comma = tag.LastIndexOf('-');
var close = tag.LastIndexOf(']');
var start = tag.Substring(open, comma - open);
var end = tag.Substring(comma + 1, close - comma - 1);
return TextSpan.FromBounds(int.Parse(start), int.Parse(end));
}).ToArray();
}
public void GoToDefinition(string expectedWindowName)
{
_editorInProc.GoToDefinition();
_editorInProc.WaitForActiveWindow(expectedWindowName);
}
public void GoToImplementation(string expectedWindowName)
{
_editorInProc.GoToImplementation();
_editorInProc.WaitForActiveWindow(expectedWindowName);
}
public void SendExplicitFocus()
=> _editorInProc.SendExplicitFocus();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Windows;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using UIAutomationClient;
using Xunit;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
/// <summary>
/// Provides a means of interacting with the Visual Studio editor by remoting calls into Visual Studio.
/// </summary>
public partial class Editor_OutOfProc : TextViewWindow_OutOfProc
{
public new Verifier Verify { get; }
private readonly Editor_InProc _editorInProc;
private readonly VisualStudioInstance _instance;
internal Editor_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
_instance = visualStudioInstance;
_editorInProc = (Editor_InProc)_textViewWindowInProc;
Verify = new Verifier(this, _instance);
}
internal override TextViewWindow_InProc CreateInProcComponent(VisualStudioInstance visualStudioInstance)
=> CreateInProcComponent<Editor_InProc>(visualStudioInstance);
public void Activate()
=> _editorInProc.Activate();
public string GetText()
=> _editorInProc.GetText();
public void SetText(string value)
=> _editorInProc.SetText(value);
public string GetCurrentLineText()
=> _editorInProc.GetCurrentLineText();
public string GetLineTextBeforeCaret()
=> _editorInProc.GetLineTextBeforeCaret();
public string GetSelectedText()
=> _editorInProc.GetSelectedText();
public string GetLineTextAfterCaret()
=> _editorInProc.GetLineTextAfterCaret();
public void MoveCaret(int position)
=> _editorInProc.MoveCaret(position);
public ImmutableArray<TextSpan> GetTagSpans(string tagId)
{
if (tagId == _instance.InlineRenameDialog.ValidRenameTag)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Rename);
}
var tagInfo = _editorInProc.GetTagSpans(tagId).ToList();
// The spans are returned in an array:
// [s1.Start, s1.Length, s2.Start, s2.Length, ...]
// Reconstruct the spans from their component parts
var builder = ArrayBuilder<TextSpan>.GetInstance();
for (var i = 0; i < tagInfo.Count; i += 2)
{
builder.Add(new TextSpan(tagInfo[i], tagInfo[i + 1]));
}
return builder.ToImmutableAndFree();
}
public void InvokeNavigateToNextHighlightedReference()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
_instance.ExecuteCommand(WellKnownCommandNames.Edit_NextHighlightedReference);
}
public string GetCurrentCompletionItem()
{
WaitForCompletionSet();
return _editorInProc.GetCurrentCompletionItem();
}
public bool IsCompletionActive()
{
WaitForCompletionSet();
return _editorInProc.IsCompletionActive();
}
public void InvokeSignatureHelp()
{
_instance.ExecuteCommand(WellKnownCommandNames.Edit_ParameterInfo);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
}
public bool IsSignatureHelpActive()
{
WaitForSignatureHelp();
return _editorInProc.IsSignatureHelpActive();
}
public Signature[] GetSignatures()
{
WaitForSignatureHelp();
return _editorInProc.GetSignatures();
}
public Signature GetCurrentSignature()
{
WaitForSignatureHelp();
return _editorInProc.GetCurrentSignature();
}
public void InvokeNavigateTo(params object[] keys)
{
_instance.ExecuteCommand(WellKnownCommandNames.Edit_GoToAll);
NavigateToSendKeys(keys);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigateTo);
}
public void SelectTextInCurrentDocument(string text)
{
PlaceCaret(text, charsOffset: -1, occurrence: 0, extendSelection: false, selectBlock: false);
PlaceCaret(text, charsOffset: 0, occurrence: 0, extendSelection: true, selectBlock: false);
}
public int GetLine() => _editorInProc.GetLine();
public int GetColumn() => _editorInProc.GetColumn();
public void DeleteText(string text)
{
SelectTextInCurrentDocument(text);
SendKeys(VirtualKey.Delete);
}
public void ReplaceText(string oldText, string newText)
=> _editorInProc.ReplaceText(oldText, newText);
public bool IsCaretOnScreen()
=> _editorInProc.IsCaretOnScreen();
public void AddWinFormButton(string buttonName)
=> _editorInProc.AddWinFormButton(buttonName);
public void DeleteWinFormButton(string buttonName)
=> _editorInProc.DeleteWinFormButton(buttonName);
public void EditWinFormButtonProperty(string buttonName, string propertyName, string propertyValue, string? propertyTypeName = null)
=> _editorInProc.EditWinFormButtonProperty(buttonName, propertyName, propertyValue, propertyTypeName);
public void EditWinFormButtonEvent(string buttonName, string eventName, string eventHandlerName)
=> _editorInProc.EditWinFormButtonEvent(buttonName, eventName, eventHandlerName);
public string? GetWinFormButtonPropertyValue(string buttonName, string propertyName)
=> _editorInProc.GetWinFormButtonPropertyValue(buttonName, propertyName);
/// <summary>
/// Sends key strokes to the active editor in Visual Studio. Various types are supported by this method:
/// <see cref="string"/> (each character will be sent separately, <see cref="char"/>, <see cref="VirtualKey"/>
/// and <see cref="KeyPress"/>.
/// </summary>
public void SendKeys(params object[] keys)
{
Activate();
VisualStudioInstance.SendKeys.Send(keys);
}
public void MessageBox(string message)
=> _editorInProc.MessageBox(message);
public IUIAutomationElement GetDialog(string dialogAutomationId)
{
var dialog = DialogHelpers.GetOpenDialogById(_instance.Shell.GetHWnd(), dialogAutomationId);
return dialog;
}
public void VerifyDialog(string dialogName, bool isOpen)
=> _editorInProc.VerifyDialog(dialogName, isOpen);
public void PressDialogButton(string dialogAutomationName, string buttonAutomationName)
=> _editorInProc.PressDialogButton(dialogAutomationName, buttonAutomationName);
public void DialogSendKeys(string dialogAutomationName, params object[] keys)
=> _editorInProc.DialogSendKeys(dialogAutomationName, keys);
public void FormatDocument()
{
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
SendKeys(new KeyPress(VirtualKey.K, ShiftState.Ctrl), new KeyPress(VirtualKey.D, ShiftState.Ctrl));
}
public void FormatDocumentViaCommand()
{
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
_editorInProc.FormatDocumentViaCommand();
}
public void FormatSelection()
{
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
SendKeys(new KeyPress(VirtualKey.K, ShiftState.Ctrl), new KeyPress(VirtualKey.F, ShiftState.Ctrl));
}
public void Paste(string text)
{
var thread = new Thread(() => Clipboard.SetText(text));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
_editorInProc.Paste();
}
public void Undo()
=> _editorInProc.Undo();
public void Redo()
=> _editorInProc.Redo();
public void NavigateToSendKeys(params object[] keys)
=> _editorInProc.SendKeysToNavigateTo(keys);
public ClassifiedToken[] GetLightbulbPreviewClassification(string menuText) =>
_editorInProc.GetLightbulbPreviewClassifications(menuText);
public bool IsUseSuggestionModeOn()
=> _editorInProc.IsUseSuggestionModeOn();
public void SetUseSuggestionMode(bool value)
{
Assert.False(IsCompletionActive());
_editorInProc.SetUseSuggestionMode(value);
}
public void WaitForActiveView(string viewName)
=> _editorInProc.WaitForActiveView(viewName);
public void WaitForActiveWindow(string windowName)
=> _editorInProc.WaitForActiveWindow(windowName);
public string[] GetErrorTags()
=> _editorInProc.GetErrorTags();
public List<string> GetF1Keyword()
=> _editorInProc.GetF1Keywords();
public void ExpandProjectNavBar()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.ExpandNavigationBar(0);
}
public void ExpandTypeNavBar()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.ExpandNavigationBar(1);
}
public void ExpandMemberNavBar()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.ExpandNavigationBar(2);
}
public string[] GetProjectNavBarItems()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetNavBarItems(0);
}
public string[] GetTypeNavBarItems()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetNavBarItems(1);
}
public string[] GetMemberNavBarItems()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetNavBarItems(2);
}
public string? GetProjectNavBarSelection()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetSelectedNavBarItem(0);
}
public string? GetTypeNavBarSelection()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetSelectedNavBarItem(1);
}
public string? GetMemberNavBarSelection()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.GetSelectedNavBarItem(2);
}
public void SelectProjectNavbarItem(string item)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.SelectNavBarItem(0, item);
}
public void SelectTypeNavBarItem(string item)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.SelectNavBarItem(1, item);
}
public void SelectMemberNavBarItem(string item)
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
_editorInProc.SelectNavBarItem(2, item);
}
public bool IsNavBarEnabled()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.NavigationBar);
return _editorInProc.IsNavBarEnabled();
}
public TextSpan[] GetKeywordHighlightTags()
=> Deserialize(_editorInProc.GetHighlightTags());
public TextSpan[] GetOutliningSpans()
{
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Outlining);
return Deserialize(_editorInProc.GetOutliningSpans());
}
private TextSpan[] Deserialize(string[] v)
{
// returned tag looks something like 'text'[12-13]
return v.Select(tag =>
{
var open = tag.LastIndexOf('[') + 1;
var comma = tag.LastIndexOf('-');
var close = tag.LastIndexOf(']');
var start = tag.Substring(open, comma - open);
var end = tag.Substring(comma + 1, close - comma - 1);
return TextSpan.FromBounds(int.Parse(start), int.Parse(end));
}).ToArray();
}
public void GoToDefinition(string expectedWindowName)
{
_editorInProc.GoToDefinition();
_editorInProc.WaitForActiveWindow(expectedWindowName);
}
public void GoToImplementation(string expectedWindowName)
{
_editorInProc.GoToImplementation();
_editorInProc.WaitForActiveWindow(expectedWindowName);
}
public void SendExplicitFocus()
=> _editorInProc.SendExplicitFocus();
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/CSharpTest2/Recommendations/BreakKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class BreakKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot()
{
await VerifyAbsenceAsync(
@"$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement()
{
await VerifyAbsenceAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration()
{
await VerifyAbsenceAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[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 = $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestEmptyStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBeforeStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$
return true;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"return true;
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlock(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIf(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterDo(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"do
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterWhile(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"while (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterFor(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for (int i = 0; i < 10; i++)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterForeach(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v in bar)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideAnonymousMethod(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = delegate {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideSwitchWithLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitchOutsideLambda(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
};
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterBreak(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"break $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClass()
{
await VerifyAbsenceAsync(@"class C
{
$$
}");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterYield(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"yield $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterSwitchInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
switch (expr) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlockInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
{
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class BreakKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot()
{
await VerifyAbsenceAsync(
@"$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement()
{
await VerifyAbsenceAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration()
{
await VerifyAbsenceAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[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 = $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestEmptyStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBeforeStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$
return true;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"return true;
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlock(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIf(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterDo(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"do
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterWhile(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"while (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterFor(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for (int i = 0; i < 10; i++)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterForeach(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v in bar)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideAnonymousMethod(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = delegate {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideSwitchWithLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitchOutsideLambda(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
};
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterBreak(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"break $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClass()
{
await VerifyAbsenceAsync(@"class C
{
$$
}");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterYield(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"yield $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterSwitchInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
switch (expr) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlockInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
{
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class MethodTests : CSharpTestBase
{
[Fact]
public void Simple1()
{
var text =
@"
class A {
void M(int x) {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.NotNull(m);
Assert.True(m.ReturnsVoid);
var x = m.Parameters[0];
Assert.Equal("x", x.Name);
Assert.Equal(SymbolKind.NamedType, x.Type.Kind);
Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug
Assert.Equal(SymbolKind.Parameter, x.Kind);
Assert.Equal(Accessibility.Private, m.DeclaredAccessibility);
}
[Fact]
public void NoParameterlessCtorForStruct()
{
var text = "struct A { A() {} }";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater.
// struct A { A() {} }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "A").WithArguments("parameterless struct constructors", "10.0").WithLocation(1, 12),
// (1,12): error CS8938: The parameterless struct constructor must be 'public'.
// struct A { A() {} }
Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "A").WithLocation(1, 12));
}
[WorkItem(537194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537194")]
[Fact]
public void DefaultCtor1()
{
Action<string, string, int, Accessibility?> check =
(source, className, ctorCount, accessibility) =>
{
var comp = CreateCompilation(source);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers(className, 0).Single();
var ctors = a.InstanceConstructors; // Note, this only returns *instance* constructors.
Assert.Equal(ctorCount, ctors.Length);
foreach (var ct in ctors)
{
Assert.Equal(
ct.IsStatic ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName,
ct.Name
);
if (accessibility != null)
Assert.Equal(accessibility, ct.DeclaredAccessibility);
}
};
Accessibility? doNotCheckAccessibility = null;
// A class without any defined constructors should generator a public constructor.
check(@"internal class A { }", "A", 1, Accessibility.Public);
// An abstract class without any defined constructors should generator a protected constructor.
check(@"abstract internal class A { }", "A", 1, Accessibility.Protected);
// A static class should not generate a default constructor
check(@"static internal class A { }", "A", 0, doNotCheckAccessibility);
// A class with a defined instance constructor should not generate a default constructor.
check(@"internal class A { A(int x) {} }", "A", 1, doNotCheckAccessibility);
// A class with only a static constructor defined should still generate a default instance constructor.
check(@"internal class A { static A(int x) {} }", "A", 1, doNotCheckAccessibility);
}
[WorkItem(537345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537345")]
[Fact]
public void Ctor1()
{
var text =
@"
class A {
A(int x) {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.InstanceConstructors.Single();
Assert.NotNull(m);
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m.Name);
Assert.True(m.ReturnsVoid);
Assert.Equal(MethodKind.Constructor, m.MethodKind);
var x = m.Parameters[0];
Assert.Equal("x", x.Name);
Assert.Equal(SymbolKind.NamedType, x.Type.Kind);
Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug
Assert.Equal(SymbolKind.Parameter, x.Kind);
Assert.Equal(Accessibility.Private, m.DeclaredAccessibility);
}
[Fact]
public void Simple2()
{
var text =
@"
class A {
void M<T>(int x) {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.NotNull(m);
Assert.True(m.ReturnsVoid);
Assert.Equal(MethodKind.Ordinary, m.MethodKind);
var x = m.Parameters[0];
Assert.Equal("x", x.Name);
Assert.Equal(SymbolKind.NamedType, x.Type.Kind);
Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug
Assert.Equal(SymbolKind.Parameter, x.Kind);
Assert.Equal(Accessibility.Private, m.DeclaredAccessibility);
}
[Fact]
public void Access1()
{
var text =
@"
class A {
void M1() {}
}
interface B {
void M2() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m1 = a.GetMembers("M1").Single() as MethodSymbol;
var b = global.GetTypeMembers("B", 0).Single();
var m2 = b.GetMembers("M2").Single() as MethodSymbol;
Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility);
Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility);
}
[Fact]
public void GenericParameter()
{
var text =
@"
public class MyList<T>
{
public void Add(T element)
{
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var mylist = global.GetTypeMembers("MyList", 1).Single();
var t1 = mylist.TypeParameters[0];
var add = mylist.GetMembers("Add").Single() as MethodSymbol;
var element = add.Parameters[0];
var t2 = element.Type;
Assert.Equal(t1, t2);
}
[Fact]
public void PartialLocation()
{
var text =
@"
public partial class A {
partial void M();
}
public partial class A {
partial void M() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M");
Assert.Equal(1, m.Length);
Assert.Equal(1, m.First().Locations.Length);
}
[Fact]
public void PartialExtractSyntaxLocation_DeclBeforeDef()
{
var text =
@"public partial class A {
partial void M();
}
public partial class A {
partial void M() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialDefinition());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).First();
var otherSymbol = m.PartialImplementationPart;
Assert.True(otherSymbol.IsPartialImplementation());
Assert.Equal(node, returnSyntax);
Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax());
}
[Fact]
public void PartialExtractSyntaxLocation_DefBeforeDecl()
{
var text =
@"public partial class A {
partial void M() {}
}
public partial class A {
partial void M();
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialDefinition());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Last();
var otherSymbol = m.PartialImplementationPart;
Assert.True(otherSymbol.IsPartialImplementation());
Assert.Equal(node, returnSyntax);
Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax());
}
[Fact]
public void PartialExtractSyntaxLocation_OnlyDef()
{
var text =
@"public partial class A {
partial void M() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialImplementation());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single().GetRoot();
var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single();
Assert.Equal(node, returnSyntax);
}
[Fact]
public void PartialExtractSyntaxLocation_OnlyDecl()
{
var text =
@"public partial class A {
partial void M();
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialDefinition());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single().GetRoot();
var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single();
Assert.Equal(node, returnSyntax);
}
[Fact]
public void FullName()
{
var text =
@"
public class A {
public string M(int x);
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.Equal("System.String A.M(System.Int32 x)", m.ToTestDisplayString());
}
[Fact]
public void TypeParameterScope()
{
var text =
@"
public interface A {
T M<T>(T t);
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
var t = m.TypeParameters[0];
Assert.Equal(t, m.Parameters[0].Type);
Assert.Equal(t, m.ReturnType);
}
[WorkItem(931142, "DevDiv/Personal")]
[Fact]
public void RefOutParameterType()
{
var text = @"public class A {
void M(ref A refp, out long outp) { }
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
var p1 = m.Parameters[0];
var p2 = m.Parameters[1];
Assert.Equal(RefKind.Ref, p1.RefKind);
Assert.Equal(RefKind.Out, p2.RefKind);
var refP = p1.Type;
Assert.Equal(TypeKind.Class, refP.TypeKind);
Assert.True(refP.IsReferenceType);
Assert.False(refP.IsValueType);
Assert.Equal("Object", refP.BaseType().Name);
Assert.Equal(2, refP.GetMembers().Length); // M + generated constructor.
Assert.Equal(1, refP.GetMembers("M").Length);
var outP = p2.Type;
Assert.Equal(TypeKind.Struct, outP.TypeKind);
Assert.False(outP.IsReferenceType);
Assert.True(outP.IsValueType);
Assert.False(outP.IsStatic);
Assert.False(outP.IsAbstract);
Assert.True(outP.IsSealed);
Assert.Equal(Accessibility.Public, outP.DeclaredAccessibility);
Assert.Equal(5, outP.Interfaces().Length);
Assert.Equal(0, outP.GetTypeMembers().Length); // Enumerable.Empty<NamedTypeSymbol>()
Assert.Equal(0, outP.GetTypeMembers(String.Empty).Length);
Assert.Equal(0, outP.GetTypeMembers(String.Empty, 0).Length);
}
[Fact]
public void RefReturn()
{
var text =
@"public class A
{
ref int M(ref int i)
{
return ref i;
}
}
";
var comp = CreateCompilationWithMscorlib45(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.Equal(RefKind.Ref, m.RefKind);
Assert.Equal(TypeKind.Struct, m.ReturnType.TypeKind);
Assert.False(m.ReturnType.IsReferenceType);
Assert.True(m.ReturnType.IsValueType);
var p1 = m.Parameters[0];
Assert.Equal(RefKind.Ref, p1.RefKind);
Assert.Equal("ref System.Int32 A.M(ref System.Int32 i)", m.ToTestDisplayString());
}
[Fact]
public void BothKindsOfCtors()
{
var text =
@"public class Test
{
public Test() {}
public static Test() {}
}";
var comp = CreateCompilation(text);
var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single();
var members = classTest.GetMembers();
Assert.Equal(2, members.Length);
}
[WorkItem(931663, "DevDiv/Personal")]
[Fact]
public void RefOutArrayParameter()
{
var text =
@"public class Test
{
public void MethodWithRefOutArray(ref int[] ary1, out string[] ary2)
{
ary2 = null;
}
}";
var comp = CreateCompilation(text);
var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single();
var method = classTest.GetMembers("MethodWithRefOutArray").Single() as MethodSymbol;
Assert.Equal(classTest, method.ContainingSymbol);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.True(method.IsDefinition);
// var paramList = (method as MethodSymbol).Parameters;
var p1 = method.Parameters[0];
var p2 = method.Parameters[1];
Assert.Equal(RefKind.Ref, p1.RefKind);
Assert.Equal(RefKind.Out, p2.RefKind);
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void InterfaceImplementsCrossTrees(string ob, string cb)
{
var text1 =
@"using System;
using System.Collections.Generic;
namespace NS
" + ob + @"
public class Abc {}
public interface IGoo<T>
{
void M(ref T t);
}
public interface I1
{
void M(ref string p);
int M1(short p1, params object[] ary);
}
public interface I2 : I1
{
void M21();
Abc M22(ref Abc p);
}
" + cb;
var text2 =
@"using System;
using System.Collections.Generic;
namespace NS.NS1
" + ob + @"
public class Impl : I2, IGoo<string>, I1
{
void IGoo<string>.M(ref string p) { }
void I1.M(ref string p) { }
public int M1(short p1, params object[] ary) { return p1; }
public void M21() {}
public Abc M22(ref Abc p) { return p; }
}
struct S<T>: IGoo<T>
{
void IGoo<T>.M(ref T t) {}
}
" + cb;
var comp = CreateCompilation(new[] { text1, text2 });
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var ns1 = ns.GetMembers("NS1").Single() as NamespaceSymbol;
var classImpl = ns1.GetTypeMembers("Impl", 0).Single() as NamedTypeSymbol;
Assert.Equal(3, classImpl.Interfaces().Length);
//
var itfc = classImpl.Interfaces().First() as NamedTypeSymbol;
Assert.Equal(1, itfc.Interfaces().Length);
itfc = itfc.Interfaces().First() as NamedTypeSymbol;
Assert.Equal("I1", itfc.Name);
// explicit interface member names include the explicit interface
var mems = classImpl.GetMembers("M");
Assert.Equal(0, mems.Length);
//var mem1 = mems.First() as MethodSymbol;
// not impl
// Assert.Equal(MethodKind.ExplicitInterfaceImplementation, mem1.MethodKind);
// Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count());
var mem1 = classImpl.GetMembers("M22").Single() as MethodSymbol;
// not impl
// Assert.Equal(0, mem1.ExplicitInterfaceImplementation.Count());
var param = mem1.Parameters.First() as ParameterSymbol;
Assert.Equal(RefKind.Ref, param.RefKind);
Assert.Equal("ref NS.Abc p", param.ToTestDisplayString());
var structImpl = ns1.GetTypeMembers("S").Single() as NamedTypeSymbol;
Assert.Equal(1, structImpl.Interfaces().Length);
itfc = structImpl.Interfaces().First() as NamedTypeSymbol;
Assert.Equal("NS.IGoo<T>", itfc.ToTestDisplayString());
//var mem2 = structImpl.GetMembers("M").Single() as MethodSymbol;
// not impl
// Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count());
}
[Fact]
public void AbstractVirtualMethodsCrossTrees()
{
var text = @"
namespace MT {
public interface IGoo {
void M0();
}
}
";
var text1 = @"
namespace N1 {
using MT;
public abstract class Abc : IGoo {
public abstract void M0();
public char M1;
public abstract object M2(ref object p1);
public virtual void M3(ulong p1, out ulong p2) { p2 = p1; }
public virtual object M4(params object[] ary) { return null; }
public static void M5<T>(T t) { }
public abstract ref int M6(ref int i);
}
}
";
var text2 = @"
namespace N1.N2 {
public class Bbc : Abc {
public override void M0() { }
public override object M2(ref object p1) { M1 = 'a'; return p1; }
public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; }
public override object M4(params object[] ary) { return null; }
public static new void M5<T>(T t) { }
public override ref int M6(ref int i) { return ref i; }
}
}
";
var comp = CreateCompilationWithMscorlib45(new[] { text, text1, text2 });
Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol;
var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol;
#region "Bbc"
var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol;
var mems = type1.GetMembers();
Assert.Equal(7, mems.Length);
// var sorted = mems.Orderby(m => m.Name).ToArray();
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.False(m0.IsAbstract);
Assert.False(m0.IsOverride);
Assert.False(m0.IsSealed);
Assert.False(m0.IsVirtual);
var m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.False(m1.IsAbstract);
Assert.True(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
var m2 = sorted[2] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.False(m2.IsAbstract);
Assert.True(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
var m3 = sorted[3] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.True(m3.IsOverride);
Assert.True(m3.IsSealed);
Assert.False(m3.IsVirtual);
var m4 = sorted[4] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.True(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.False(m4.IsVirtual);
var m5 = sorted[5] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
var m6 = sorted[6] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.False(m6.IsAbstract);
Assert.True(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
#region "Abc"
var type2 = type1.BaseType();
Assert.Equal("Abc", type2.Name);
mems = type2.GetMembers();
Assert.Equal(8, mems.Length);
sorted = (from m in mems
orderby m.Name
select m).ToArray();
var mm = sorted[2] as FieldSymbol;
Assert.Equal("M1", mm.Name);
Assert.False(mm.IsAbstract);
Assert.False(mm.IsOverride);
Assert.False(mm.IsSealed);
Assert.False(mm.IsVirtual);
m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.Equal(Accessibility.Protected, m0.DeclaredAccessibility);
m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.True(m1.IsAbstract);
Assert.False(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
m2 = sorted[3] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.True(m2.IsAbstract);
Assert.False(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
m3 = sorted[4] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.False(m3.IsOverride);
Assert.False(m3.IsSealed);
Assert.True(m3.IsVirtual);
m4 = sorted[5] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.False(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.True(m4.IsVirtual);
m5 = sorted[6] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
m6 = sorted[7] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.True(m6.IsAbstract);
Assert.False(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
}
[WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")]
[Fact]
public void AbstractVirtualMethodsCrossComps()
{
var text = @"
namespace MT {
public interface IGoo {
void M0();
}
}
";
var text1 = @"
namespace N1 {
using MT;
public abstract class Abc : IGoo {
public abstract void M0();
public char M1;
public abstract object M2(ref object p1);
public virtual void M3(ulong p1, out ulong p2) { p2 = p1; }
public virtual object M4(params object[] ary) { return null; }
public static void M5<T>(T t) { }
public abstract ref int M6(ref int i);
}
}
";
var text2 = @"
namespace N1.N2 {
public class Bbc : Abc {
public override void M0() { }
public override object M2(ref object p1) { M1 = 'a'; return p1; }
public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; }
public override object M4(params object[] ary) { return null; }
public static new void M5<T>(T t) { }
public override ref int M6(ref int i) { return ref i; }
}
}
";
var comp1 = CreateCompilationWithMscorlib45(text);
var compRef1 = new CSharpCompilationReference(comp1);
var comp2 = CreateCompilationWithMscorlib45(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2");
//Compilation.Create(outputName: "Test2", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) },
// references: new MetadataReference[] { compRef1, GetCorlibReference() });
var compRef2 = new CSharpCompilationReference(comp2);
var comp = CreateCompilationWithMscorlib45(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3");
//Compilation.Create(outputName: "Test3", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) },
// references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() });
Assert.Equal(0, comp1.GetDiagnostics().Count());
Assert.Equal(0, comp2.GetDiagnostics().Count());
Assert.Equal(0, comp.GetDiagnostics().Count());
//string errs = String.Empty;
//foreach (var e in comp.GetDiagnostics())
//{
// errs += e.Info.ToString() + "\r\n";
//}
//Assert.Equal("Errs", errs);
var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol;
var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol;
#region "Bbc"
var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol;
var mems = type1.GetMembers();
Assert.Equal(7, mems.Length);
// var sorted = mems.Orderby(m => m.Name).ToArray();
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.False(m0.IsAbstract);
Assert.False(m0.IsOverride);
Assert.False(m0.IsSealed);
Assert.False(m0.IsVirtual);
var m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.False(m1.IsAbstract);
Assert.True(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
var m2 = sorted[2] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.False(m2.IsAbstract);
Assert.True(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
var m3 = sorted[3] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.True(m3.IsOverride);
Assert.True(m3.IsSealed);
Assert.False(m3.IsVirtual);
var m4 = sorted[4] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.True(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.False(m4.IsVirtual);
var m5 = sorted[5] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
var m6 = sorted[6] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.False(m6.IsAbstract);
Assert.True(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
#region "Abc"
var type2 = type1.BaseType();
Assert.Equal("Abc", type2.Name);
mems = type2.GetMembers();
Assert.Equal(8, mems.Length);
sorted = (from m in mems
orderby m.Name
select m).ToArray();
var mm = sorted[2] as FieldSymbol;
Assert.Equal("M1", mm.Name);
Assert.False(mm.IsAbstract);
Assert.False(mm.IsOverride);
Assert.False(mm.IsSealed);
Assert.False(mm.IsVirtual);
m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.False(m0.IsAbstract);
Assert.False(m0.IsOverride);
Assert.False(m0.IsSealed);
Assert.False(m0.IsVirtual);
m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.True(m1.IsAbstract);
Assert.False(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
m2 = sorted[3] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.True(m2.IsAbstract);
Assert.False(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
m3 = sorted[4] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.False(m3.IsOverride);
Assert.False(m3.IsSealed);
Assert.True(m3.IsVirtual);
m4 = sorted[5] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.False(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.True(m4.IsVirtual);
m5 = sorted[6] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
m6 = sorted[7] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.True(m6.IsAbstract);
Assert.False(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
}
[Fact]
public void OverloadMethodsCrossTrees()
{
var text = @"
using System;
namespace NS
{
public class A
{
public void Overloads(ushort p) { }
public void Overloads(A p) { }
}
}
";
var text1 = @"
namespace NS
{
using System;
public class B : A
{
public void Overloads(ref A p) { }
public string Overloads(B p) { return null; }
protected long Overloads(A p, long p2) { return p2; }
}
}
";
var text2 = @"
namespace NS {
public class Test {
public class C : B {
protected long Overloads(A p, B p2) { return 1; }
}
public static void Main() {
var obj = new C();
A a = obj;
obj.Overloads(ref a);
obj.Overloads(obj);
}
}
}
";
var comp = CreateCompilation(new[] { text, text1, text2 });
// Not impl errors
// Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
var mems = type1.GetMembers();
Assert.Equal(2, mems.Length);
var mems1 = type1.BaseType().GetMembers();
Assert.Equal(4, mems1.Length);
var mems2 = type1.BaseType().BaseType().GetMembers();
Assert.Equal(3, mems2.Length);
var list = new List<Symbol>();
list.AddRange(mems);
list.AddRange(mems1);
list.AddRange(mems2);
var sorted = (from m in list
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[1] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[2] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
var m1 = sorted[3] as MethodSymbol;
Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString());
m1 = sorted[4] as MethodSymbol;
Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString());
m1 = sorted[5] as MethodSymbol;
Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString());
m1 = sorted[6] as MethodSymbol;
Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString());
m1 = sorted[7] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString());
m1 = sorted[8] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString());
}
[WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")]
[Fact]
public void OverloadMethodsCrossComps()
{
var text = @"
namespace NS
{
public class A
{
public void Overloads(ushort p) { }
public void Overloads(A p) { }
}
}
";
var text1 = @"
namespace NS
{
public class B : A
{
public void Overloads(ref A p) { }
public string Overloads(B p) { return null; }
protected long Overloads(A p, long p2) { return p2; }
}
}
";
var text2 = @"
namespace NS {
public class Test {
public class C : B {
protected long Overloads(A p, B p2) { return 1; }
}
public static void Main() {
C obj = new C(); // var NotImpl ???
A a = obj;
obj.Overloads(ref a);
obj.Overloads(obj);
}
}
}
";
var comp1 = CreateCompilation(text);
var compRef1 = new CSharpCompilationReference(comp1);
var comp2 = CreateCompilation(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2");
//Compilation.Create(outputName: "Test2", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) },
// references: new MetadataReference[] { compRef1, GetCorlibReference() });
var compRef2 = new CSharpCompilationReference(comp2);
var comp = CreateCompilation(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3");
//Compilation.Create(outputName: "Test3", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) },
// references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() });
Assert.Equal(0, comp1.GetDiagnostics().Count());
Assert.Equal(0, comp2.GetDiagnostics().Count());
Assert.Equal(0, comp.GetDiagnostics().Count());
//string errs = String.Empty;
//foreach (var e in comp.GetDiagnostics())
//{
// errs += e.Info.ToString() + "\r\n";
//}
//Assert.Equal(String.Empty, errs);
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
var mems = type1.GetMembers();
Assert.Equal(2, mems.Length);
var mems1 = type1.BaseType().GetMembers();
Assert.Equal(4, mems1.Length);
var mems2 = type1.BaseType().BaseType().GetMembers();
Assert.Equal(3, mems2.Length);
var list = new List<Symbol>();
list.AddRange(mems);
list.AddRange(mems1);
list.AddRange(mems2);
var sorted = (from m in list
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[1] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[2] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
var m1 = sorted[3] as MethodSymbol;
Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString());
m1 = sorted[4] as MethodSymbol;
Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString());
m1 = sorted[5] as MethodSymbol;
Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString());
m1 = sorted[6] as MethodSymbol;
Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString());
m1 = sorted[7] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString());
m1 = sorted[8] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString());
}
[WorkItem(537754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537754")]
[Fact]
public void PartialMethodsCrossTrees()
{
var text = @"
namespace NS
{
public partial struct PS
{
partial void M0(string p);
partial class GPC<T>
{
partial void GM0(T p1, short p2);
}
}
}
";
var text1 = @"
namespace NS
{
partial struct PS
{
partial void M0(string p) { }
partial void M1(params ulong[] ary);
public partial class GPC<T>
{
partial void GM0(T p1, short p2) { }
partial void GM1<V>(T p1, V p2);
}
}
}
";
var text2 = @"
namespace NS
{
partial struct PS
{
partial void M1(params ulong[] ary) {}
partial void M2(sbyte p);
partial class GPC<T>
{
partial void GM1<V>(T p1, V p2) { }
}
}
}
";
var comp = CreateCompilation(new[] { text, text1, text2 });
Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("PS", 0).Single() as NamedTypeSymbol;
// Bug
// Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
Assert.Equal(3, type1.Locations.Length);
Assert.False(type1.IsReferenceType);
Assert.True(type1.IsValueType);
var mems = type1.GetMembers();
Assert.Equal(5, mems.Length);
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility);
Assert.Equal(3, m0.Locations.Length);
var m2 = sorted[2] as MethodSymbol;
Assert.Equal("M0", m2.Name);
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility);
Assert.Equal(1, m2.Locations.Length);
Assert.True(m2.ReturnsVoid);
var m3 = sorted[3] as MethodSymbol;
Assert.Equal("M1", m3.Name);
Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility);
Assert.Equal(1, m3.Locations.Length);
var m4 = sorted[4] as MethodSymbol;
Assert.Equal("M2", m4.Name);
Assert.Equal(Accessibility.Private, m4.DeclaredAccessibility);
Assert.Equal(1, m4.Locations.Length);
#region "GPC"
var type2 = sorted[1] as NamedTypeSymbol;
Assert.Equal("NS.PS.GPC<T>", type2.ToTestDisplayString());
Assert.True(type2.IsNestedType());
// Bug
Assert.Equal(Accessibility.Public, type2.DeclaredAccessibility);
Assert.Equal(3, type2.Locations.Length);
Assert.False(type2.IsValueType);
Assert.True(type2.IsReferenceType);
mems = type2.GetMembers();
// Assert.Equal(3, mems.Count());
sorted = (from m in mems
orderby m.Name
select m).ToArray();
m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility);
Assert.Equal(3, m0.Locations.Length);
var mm = sorted[1] as MethodSymbol;
Assert.Equal("GM0", mm.Name);
Assert.Equal(Accessibility.Private, mm.DeclaredAccessibility);
Assert.Equal(1, mm.Locations.Length);
m2 = sorted[2] as MethodSymbol;
Assert.Equal("GM1", m2.Name);
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility);
Assert.Equal(1, m2.Locations.Length);
Assert.True(m2.ReturnsVoid);
#endregion
}
[WorkItem(537755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537755")]
[Fact]
public void PartialMethodsWithRefParams()
{
var text = @"
namespace NS
{
public partial class PC
{
partial void M0(ref long p);
partial void M1(ref string p);
}
partial class PC
{
partial void M0(ref long p) {}
partial void M1(ref string p) {}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("PC", 0).Single() as NamedTypeSymbol;
Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
Assert.Equal(2, type1.Locations.Length);
Assert.True(type1.IsReferenceType);
Assert.False(type1.IsValueType);
var mems = type1.GetMembers();
// Bug: actual 5
Assert.Equal(3, mems.Length);
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m1 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m1.Name);
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility);
Assert.Equal(2, m1.Locations.Length);
var m2 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m2.Name);
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility);
Assert.Equal(1, m2.Locations.Length);
Assert.True(m2.ReturnsVoid);
var m3 = sorted[2] as MethodSymbol;
Assert.Equal("M1", m3.Name);
Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility);
Assert.Equal(1, m3.Locations.Length);
Assert.True(m3.ReturnsVoid);
}
[WorkItem(2358, "DevDiv_Projects/Roslyn")]
[Fact]
public void ExplicitInterfaceImplementation()
{
var text = @"
interface ISubFuncProp
{
}
interface Interface3
{
System.Collections.Generic.List<ISubFuncProp> Goo();
}
interface Interface3Derived : Interface3
{
}
public class DerivedClass : Interface3Derived
{
System.Collections.Generic.List<ISubFuncProp> Interface3.Goo()
{
return null;
}
System.Collections.Generic.List<ISubFuncProp> Goo()
{
return null;
}
}";
var comp = CreateCompilation(text);
var derivedClass = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("DerivedClass")[0];
var members = derivedClass.GetMembers();
Assert.Equal(3, members.Length);
}
[Fact]
public void SubstitutedExplicitInterfaceImplementation()
{
var text = @"
public class A<T>
{
public interface I<U>
{
void M<V>(T t, U u, V v);
}
}
public class B<Q, R> : A<Q>.I<R>
{
void A<Q>.I<R>.M<S>(Q q, R r, S s) { }
}
public class C : B<int, long>
{
}";
var comp = CreateCompilation(text);
var classB = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("B").Single();
var classBTypeArguments = classB.TypeArguments();
Assert.Equal(2, classBTypeArguments.Length);
Assert.Equal("Q", classBTypeArguments[0].Name);
Assert.Equal("R", classBTypeArguments[1].Name);
var classBMethodM = (MethodSymbol)classB.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal));
var classBMethodMTypeParameters = classBMethodM.TypeParameters;
Assert.Equal(1, classBMethodMTypeParameters.Length);
Assert.Equal("S", classBMethodMTypeParameters[0].Name);
var classBMethodMParameters = classBMethodM.Parameters;
Assert.Equal(3, classBMethodMParameters.Length);
Assert.Equal(classBTypeArguments[0], classBMethodMParameters[0].Type);
Assert.Equal(classBTypeArguments[1], classBMethodMParameters[1].Type);
Assert.Equal(classBMethodMTypeParameters[0], classBMethodMParameters[2].Type);
var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").Single();
var classCBase = classC.BaseType();
Assert.Equal(classB, classCBase.ConstructedFrom);
var classCBaseTypeArguments = classCBase.TypeArguments();
Assert.Equal(2, classCBaseTypeArguments.Length);
Assert.Equal(SpecialType.System_Int32, classCBaseTypeArguments[0].SpecialType);
Assert.Equal(SpecialType.System_Int64, classCBaseTypeArguments[1].SpecialType);
var classCBaseMethodM = (MethodSymbol)classCBase.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal));
Assert.NotEqual(classBMethodM, classCBaseMethodM);
var classCBaseMethodMTypeParameters = classCBaseMethodM.TypeParameters;
Assert.Equal(1, classCBaseMethodMTypeParameters.Length);
Assert.Equal("S", classCBaseMethodMTypeParameters[0].Name);
var classCBaseMethodMParameters = classCBaseMethodM.Parameters;
Assert.Equal(3, classCBaseMethodMParameters.Length);
Assert.Equal(classCBaseTypeArguments[0], classCBaseMethodMParameters[0].Type);
Assert.Equal(classCBaseTypeArguments[1], classCBaseMethodMParameters[1].Type);
Assert.Equal(classCBaseMethodMTypeParameters[0], classCBaseMethodMParameters[2].Type);
}
#region Regressions
[WorkItem(527149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527149")]
[Fact]
public void MethodWithParamsInParameters()
{
var text =
@"class C
{
void F1(params int[] a) { }
}
";
var comp = CreateEmptyCompilation(text);
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var f1 = c.GetMembers("F1").Single() as MethodSymbol;
Assert.Equal("void C.F1(params System.Int32[missing][] a)", f1.ToTestDisplayString());
}
[WorkItem(537352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537352")]
[Fact]
public void Arglist()
{
string code = @"
class AA
{
public static int Method1(__arglist)
{
}
}";
var comp = CreateCompilation(code);
NamedTypeSymbol nts = comp.Assembly.GlobalNamespace.GetTypeMembers()[0];
Assert.Equal("AA", nts.ToTestDisplayString());
Assert.Empty(comp.GetDeclarationDiagnostics());
Assert.Equal("System.Int32 AA.Method1(__arglist)", nts.GetMembers("Method1").Single().ToTestDisplayString());
}
[WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")]
[Fact]
public void ExpImpInterfaceWithGlobal()
{
var text = @"
using System;
namespace N1
{
interface I1
{
int Method();
}
}
namespace N2
{
class ExpImpl : N1.I1
{
int global::N1.I1.Method()
{
return 42;
}
ExpImpl(){}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("ExpImpl", 0).Single() as NamedTypeSymbol;
var m1 = type1.GetMembers().FirstOrDefault() as MethodSymbol;
Assert.Equal("System.Int32 N2.ExpImpl.N1.I1.Method()", m1.ToTestDisplayString());
var em1 = m1.ExplicitInterfaceImplementations.First() as MethodSymbol;
Assert.Equal("System.Int32 N1.I1.Method()", em1.ToTestDisplayString());
}
[WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")]
[Fact]
public void BaseInterfaceNameWithAlias()
{
var text = @"
using N1Alias = N1;
namespace N1
{
interface I1 {}
}
namespace N2
{
class N1Alias {}
class Test : N1Alias::I1
{
static int Main()
{
Test t = new Test();
return 0;
}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
var n2 = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol;
var test = n2.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var bt = test.Interfaces().Single() as NamedTypeSymbol;
Assert.Equal("N1.I1", bt.ToTestDisplayString());
}
[WorkItem(538209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538209")]
[Fact]
public void ParameterAccessibility01()
{
var text = @"
using System;
class MyClass
{
private class MyInner
{
public int MyMeth(MyInner2 arg)
{
return arg.intI;
}
}
protected class MyInner2
{
public int intI = 2;
}
public static int Main()
{
MyInner MI = new MyInner();
if (MI.MyMeth(new MyInner2()) == 2)
{
return 0;
}
else
{
return 1;
}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
}
[WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")]
[Fact]
public void MethodsWithSameSigDiffReturnType()
{
var text = @"
class Test
{
public int M1()
{
}
float M1()
{
}
}
";
var comp = CreateCompilation(text);
var test = comp.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var members = test.GetMembers("M1");
Assert.Equal(2, members.Length);
Assert.Equal("System.Int32 Test.M1()", members[0].ToTestDisplayString());
Assert.Equal("System.Single Test.M1()", members[1].ToTestDisplayString());
}
[Fact]
public void OverriddenMethod01()
{
var text = @"
class A
{
public virtual void F(object[] args) {}
}
class B : A
{
public override void F(params object[] args) {}
public static void Main(B b)
{
b.F(// yes, there is a parse error here
}
}
";
var comp = CreateCompilation(text);
var a = comp.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol;
var b = comp.GlobalNamespace.GetTypeMembers("B").Single() as NamedTypeSymbol;
var f = b.GetMembers("F").Single() as MethodSymbol;
Assert.True(f.IsOverride);
var f2 = f.OverriddenMethod;
Assert.NotNull(f2);
Assert.Equal("A", f2.ContainingSymbol.Name);
}
#endregion
[WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
[Fact]
public void MethodEscapedIdentifier()
{
var text = @"
interface @void { @void @return(@void @in); };
class @int { virtual @int @float(@int @in); };
class C1 : @int, @void
{
@void @void.@return(@void @in) { return null; }
override @int @float(@int @in) { return null; }
}
";
var comp = CreateCompilation(Parse(text));
NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single();
// Per explanation from NGafter:
//
// We intentionally escape keywords that appear in the type qualification of the interface name
// on interface implementation members. That is necessary to distinguish I<int>.F from I<@int>.F,
// for example, which might both be members in a class. An alternative would be to stop using the
// abbreviated names for the built-in types, but since we may want to use these names in
// diagnostics the @-escaped version is preferred.
//
MethodSymbol mreturn = (MethodSymbol)c1.GetMembers("@void.return").Single();
Assert.Equal("@void.return", mreturn.Name);
Assert.Equal("C1.@void.@return(@void)", mreturn.ToString());
NamedTypeSymbol rvoid = (NamedTypeSymbol)mreturn.ReturnType;
Assert.Equal("void", rvoid.Name);
Assert.Equal("@void", rvoid.ToString());
MethodSymbol mvoidreturn = (MethodSymbol)mreturn.ExplicitInterfaceImplementations.Single();
Assert.Equal("return", mvoidreturn.Name);
Assert.Equal("@void.@return(@void)", mvoidreturn.ToString());
ParameterSymbol pin = mreturn.Parameters.Single();
Assert.Equal("in", pin.Name);
Assert.Equal("@in", pin.ToDisplayString(
new SymbolDisplayFormat(
parameterOptions: SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)));
MethodSymbol mfloat = (MethodSymbol)c1.GetMembers("float").Single();
Assert.Equal("float", mfloat.Name);
Assert.Empty(c1.GetMembers("@float"));
}
[Fact]
public void ExplicitInterfaceImplementationSimple()
{
string text = @"
interface I
{
void Method();
}
class C : I
{
void I.Method() { }
}
";
var comp = CreateCompilation(Parse(text));
var globalNamespace = comp.GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, explicitImpl);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[Fact]
public void ExplicitInterfaceImplementationCorLib()
{
string text = @"
class F : System.IFormattable
{
string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider)
{
return null;
}
}
";
var comp = CreateCompilation(Parse(text));
var globalNamespace = comp.GlobalNamespace;
var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("System").Single();
var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("IFormattable").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("ToString").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("F").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classMethod = (MethodSymbol)@class.GetMembers("System.IFormattable.ToString").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, explicitImpl);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[Fact]
public void ExplicitInterfaceImplementationRef()
{
string text = @"
interface I
{
ref int Method(ref int i);
}
class C : I
{
ref int I.Method(ref int i) { return ref i; }
}
";
var comp = CreateCompilationWithMscorlib45(text);
var globalNamespace = comp.GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
Assert.Equal(RefKind.Ref, interfaceMethod.RefKind);
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
Assert.Equal(RefKind.Ref, classMethod.RefKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, explicitImpl);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[Fact]
public void ExplicitInterfaceImplementationGeneric()
{
string text = @"
namespace Namespace
{
interface I<T>
{
void Method(T t);
}
}
class IC : Namespace.I<int>
{
void Namespace.I<int>.Method(int i) { }
}
";
var comp = CreateCompilation(Parse(text));
var globalNamespace = comp.GlobalNamespace;
var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("Namespace").Single();
var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("I", 1).Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IC").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Single();
var classMethod = (MethodSymbol)@class.GetMembers("Namespace.I<System.Int32>.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterface, explicitImpl.ContainingType);
Assert.Equal(substitutedInterfaceMethod.OriginalDefinition, explicitImpl.OriginalDefinition);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
var explicitOverrideImplementedMethod = explicitOverride.ImplementedMethod;
Assert.Equal(substitutedInterface, explicitOverrideImplementedMethod.GetContainingType(context).GetInternalSymbol());
Assert.Equal(substitutedInterfaceMethod.Name, explicitOverrideImplementedMethod.Name);
Assert.Equal(substitutedInterfaceMethod.Arity, explicitOverrideImplementedMethod.GenericParameterCount);
context.Diagnostics.Verify();
}
[Fact()]
public void TestMetadataVirtual()
{
string text = @"
class C
{
virtual void Method1() { }
virtual void Method2() { }
void Method3() { }
void Method4() { }
}
";
var comp = CreateCompilation(Parse(text));
var @class = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single();
var method1 = (SourceMemberMethodSymbol)@class.GetMembers("Method1").Single();
var method2 = (SourceMemberMethodSymbol)@class.GetMembers("Method2").Single();
var method3 = (SourceMemberMethodSymbol)@class.GetMembers("Method3").Single();
var method4 = (SourceMemberMethodSymbol)@class.GetMembers("Method4").Single();
Assert.True(method1.IsVirtual);
Assert.True(method2.IsVirtual);
Assert.False(method3.IsVirtual);
Assert.False(method4.IsVirtual);
//1 and 3 - read before set
Assert.True(((Cci.IMethodDefinition)method1.GetCciAdapter()).IsVirtual);
Assert.False(((Cci.IMethodDefinition)method3.GetCciAdapter()).IsVirtual);
//2 and 4 - set before read
method2.EnsureMetadataVirtual();
method4.EnsureMetadataVirtual();
//can set twice (e.g. if the method implicitly implements more than one interface method)
method2.EnsureMetadataVirtual();
method4.EnsureMetadataVirtual();
Assert.True(((Cci.IMethodDefinition)method2.GetCciAdapter()).IsVirtual);
Assert.True(((Cci.IMethodDefinition)method4.GetCciAdapter()).IsVirtual);
//API view unchanged
Assert.True(method1.IsVirtual);
Assert.True(method2.IsVirtual);
Assert.False(method3.IsVirtual);
Assert.False(method4.IsVirtual);
}
[Fact]
public void ExplicitStaticConstructor()
{
string text = @"
class C
{
static C() { }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName);
Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind);
Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility);
Assert.True(staticConstructor.IsStatic, "Static constructor should be static");
Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType);
}
[Fact]
public void ImplicitStaticConstructor()
{
string text = @"
class C
{
static int f = 1; //initialized in implicit static constructor
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (4,16): warning CS0414: The field 'C.f' is assigned but its value is never used
// static int f = 1; //initialized in implicit static constructor
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f")
);
var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName);
Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind);
Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility);
Assert.True(staticConstructor.IsStatic, "Static constructor should be static");
Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType);
}
[WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")]
[Fact]
public void AccessorMethodAccessorOverriding()
{
var text = @"
public class A
{
public virtual int P { get; set; }
}
public class B : A
{
public virtual int get_P() { return 0; }
}
public class C : B
{
public override int P { get; set; }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var globalNamespace = comp.GlobalNamespace;
var classA = globalNamespace.GetMember<NamedTypeSymbol>("A");
var classB = globalNamespace.GetMember<NamedTypeSymbol>("B");
var classC = globalNamespace.GetMember<NamedTypeSymbol>("C");
var methodA = classA.GetMember<PropertySymbol>("P").GetMethod;
var methodB = classB.GetMember<MethodSymbol>("get_P");
var methodC = classC.GetMember<PropertySymbol>("P").GetMethod;
var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")]
[Fact]
public void MethodAccessorMethodOverriding()
{
var text = @"
public class A
{
public virtual int get_P() { return 0; }
}
public class B : A
{
public virtual int P { get; set; }
}
public class C : B
{
public override int get_P() { return 0; }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var globalNamespace = comp.GlobalNamespace;
var classA = globalNamespace.GetMember<NamedTypeSymbol>("A");
var classB = globalNamespace.GetMember<NamedTypeSymbol>("B");
var classC = globalNamespace.GetMember<NamedTypeSymbol>("C");
var methodA = classA.GetMember<MethodSymbol>("get_P");
var methodB = classB.GetMember<PropertySymbol>("P").GetMethod;
var methodC = classC.GetMember<MethodSymbol>("get_P");
var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[WorkItem(543444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543444")]
[Fact]
public void BadArityInOperatorDeclaration()
{
var text =
@"class A
{
public static bool operator true(A x, A y) { return false; }
}
class B
{
public static B operator *(B x) { return null; }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (3,33): error CS1020: Overloadable binary operator expected
// public static bool operator true(A x, A y) { return false; }
Diagnostic(ErrorCode.ERR_OvlBinaryOperatorExpected, "true"),
// (8,30): error CS1019: Overloadable unary operator expected
// public static B operator *(B x) { return null; }
Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "*"),
// (3,33): error CS0216: The operator 'A.operator true(A, A)' requires a matching operator 'false' to also be defined
// public static bool operator true(A x, A y) { return false; }
Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("A.operator true(A, A)", "false")
);
}
[WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")]
[Fact]
public void UserDefinedOperatorLocation()
{
var source = @"
public class C
{
public static C operator +(C c) { return null; }
}
";
var keywordPos = source.IndexOf('+');
var parenPos = source.IndexOf('(');
var comp = CreateCompilation(source);
var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single();
var span = symbol.Locations.Single().SourceSpan;
Assert.Equal(keywordPos, span.Start);
Assert.Equal(parenPos, span.End);
}
[WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")]
[Fact]
public void UserDefinedConversionLocation()
{
var source = @"
public class C
{
public static explicit operator string(C c) { return null; }
}
";
var keywordPos = source.IndexOf("string", StringComparison.Ordinal);
var parenPos = source.IndexOf('(');
var comp = CreateCompilation(source);
var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ExplicitConversionName).Single();
var span = symbol.Locations.Single().SourceSpan;
Assert.Equal(keywordPos, span.Start);
Assert.Equal(parenPos, span.End);
}
[WorkItem(787708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/787708")]
[Fact]
public void PartialAsyncMethodInTypeWithAttributes()
{
var source = @"
using System;
class Attr : Attribute
{
public int P { get; set; }
}
[Attr(P = F)]
partial class C
{
const int F = 1;
partial void M();
async partial void M() { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (15,24): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async partial void M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M"));
}
[WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")]
[Fact]
public void SubstitutedParameterEquality()
{
var source = @"
class C
{
void M<T>(T t) { }
}
";
var comp = CreateCompilation(source);
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var method = type.GetMember<MethodSymbol>("M");
var constructedMethod1 = method.Construct(type);
var constructedMethod2 = method.Construct(type);
Assert.Equal(constructedMethod1, constructedMethod2);
Assert.NotSame(constructedMethod1, constructedMethod2);
var substitutedParameter1 = constructedMethod1.Parameters.Single();
var substitutedParameter2 = constructedMethod2.Parameters.Single();
Assert.Equal(substitutedParameter1, substitutedParameter2);
Assert.NotSame(substitutedParameter1, substitutedParameter2);
}
[WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")]
[Fact]
public void ReducedExtensionMethodParameterEquality()
{
var source = @"
static class C
{
static void M(this int i, string s) { }
}
";
var comp = CreateCompilation(source);
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var method = type.GetMember<MethodSymbol>("M");
var reducedMethod1 = method.ReduceExtensionMethod();
var reducedMethod2 = method.ReduceExtensionMethod();
Assert.Equal(reducedMethod1, reducedMethod2);
Assert.NotSame(reducedMethod1, reducedMethod2);
var extensionParameter1 = reducedMethod1.Parameters.Single();
var extensionParameter2 = reducedMethod2.Parameters.Single();
Assert.Equal(extensionParameter1, extensionParameter2);
Assert.NotSame(extensionParameter1, extensionParameter2);
}
[Fact]
public void RefReturningVoidMethod()
{
var source = @"
static class C
{
static ref void M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,16): error CS1547: Keyword 'void' cannot be used in this context
// static ref void M() { }
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 16)
);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturningVoidMethod()
{
var source = @"
static class C
{
static ref readonly void M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,25): error CS1547: Keyword 'void' cannot be used in this context
// static ref readonly void M() { }
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 25)
);
}
[Fact]
public void RefReturningVoidMethodNested()
{
var source = @"
static class C
{
static void Main()
{
ref void M() { }
}
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,13): error CS1547: Keyword 'void' cannot be used in this context
// ref void M() { }
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(6, 13),
// (6,18): warning CS8321: The local function 'M' is declared but never used
// ref void M() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M").WithArguments("M").WithLocation(6, 18)
);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturningVoidMethodNested()
{
var source = @"
static class C
{
static void Main()
{
// valid
ref readonly int M1() {throw null;}
// not valid
ref readonly void M2() {M1(); throw null;}
M2();
}
}
";
var parseOptions = TestOptions.Regular;
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,22): error CS1547: Keyword 'void' cannot be used in this context
// ref readonly void M2() {M1(); throw null;}
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(10, 22)
);
}
[Fact]
public void RefReturningAsyncMethod()
{
var source = @"
static class C
{
static async ref int M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,18): error CS1073: Unexpected token 'ref'
// static async ref int M() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18),
// (4,26): 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.
// static async ref int M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 26),
// (4,26): error CS0161: 'C.M()': not all code paths return a value
// static async ref int M() { }
Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 26)
);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturningAsyncMethod()
{
var source = @"
static class C
{
static async ref readonly int M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,18): error CS1073: Unexpected token 'ref'
// static async ref readonly int M() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18),
// (4,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// static async ref readonly int M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 35),
// (4,35): error CS0161: 'C.M()': not all code paths return a value
// static async ref readonly int M() { }
Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 35)
);
}
[Fact]
public void StaticMethodDoesNotRequireInstanceReceiver()
{
var source = @"
class C
{
public static int M() => 42;
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.False(method.RequiresInstanceReceiver);
}
[Fact]
public void InstanceMethodRequiresInstanceReceiver()
{
var source = @"
class C
{
public int M() => 42;
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.True(method.RequiresInstanceReceiver);
}
[Fact]
public void OrdinaryMethodIsNotConditional()
{
var source = @"
class C
{
public void M() {}
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.False(method.IsConditional);
}
[Fact]
public void ConditionalMethodIsConditional()
{
var source = @"
using System.Diagnostics;
class C
{
[Conditional(""Debug"")]
public void M() {}
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.True(method.IsConditional);
}
[Fact]
public void ConditionalMethodOverrideIsConditional()
{
var source = @"
using System.Diagnostics;
class Base
{
[Conditional(""Debug"")]
public virtual void M() {}
}
class Derived : Base
{
public override void M() {}
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("Derived.M");
Assert.True(method.IsConditional);
}
[Fact]
public void InvalidConditionalMethodIsConditional()
{
var source = @"
using System.Diagnostics;
class C
{
[Conditional(""Debug"")]
public int M() => 42;
}";
var compilation = CreateCompilation(source).VerifyDiagnostics(
// (5,6): error CS0578: The Conditional attribute is not valid on 'C.M()' because its return type is not void
// [Conditional("Debug")]
Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""Debug"")").WithArguments("C.M()").WithLocation(5, 6));
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.True(method.IsConditional);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnNonPartial()
{
var source = @"
class C
{
void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.False(m.IsPartialDefinition);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnPartialDefinitionOnly()
{
var source = @"
partial class C
{
partial void M();
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.Null(m.PartialImplementationPart);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionWithPartialImplementation()
{
var source = @"
partial class C
{
partial void M();
partial void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.False(m.PartialImplementationPart.IsPartialDefinition);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnPartialImplementation_NonPartialClass()
{
var source = @"
class C
{
partial void M();
partial void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0751: A partial method must be declared within a partial type
// partial void M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(4, 18),
// (5,18): error CS0751: A partial method must be declared within a partial type
// partial void M() {}
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(5, 18)
);
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.False(m.PartialImplementationPart.IsPartialDefinition);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnPartialImplementationOnly()
{
var source = @"
partial class C
{
partial void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M()'
// partial void M() {}
Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M()").WithLocation(4, 18)
);
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.False(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.Null(m.PartialImplementationPart);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinition_ReturnsFalseFromMetadata()
{
var source = @"
public partial class C
{
public partial void M();
public partial void M() {}
}
";
CompileAndVerify(source,
sourceSymbolValidator: module =>
{
var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.False(m.PartialImplementationPart.IsPartialDefinition);
},
symbolValidator: module =>
{
var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol();
Assert.False(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.Null(m.PartialImplementationPart);
});
}
[Fact]
public void IsPartialDefinition_OnPartialExtern()
{
var source = @"
public partial class C
{
private partial void M();
private extern partial void M();
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var syntax = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntax);
var methods = syntax.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToArray();
var partialDef = model.GetDeclaredSymbol(methods[0]);
Assert.True(partialDef.IsPartialDefinition);
var partialImpl = model.GetDeclaredSymbol(methods[1]);
Assert.False(partialImpl.IsPartialDefinition);
Assert.Same(partialDef.PartialImplementationPart, partialImpl);
Assert.Same(partialImpl.PartialDefinitionPart, partialDef);
Assert.Null(partialDef.PartialDefinitionPart);
Assert.Null(partialImpl.PartialImplementationPart);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class MethodTests : CSharpTestBase
{
[Fact]
public void Simple1()
{
var text =
@"
class A {
void M(int x) {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.NotNull(m);
Assert.True(m.ReturnsVoid);
var x = m.Parameters[0];
Assert.Equal("x", x.Name);
Assert.Equal(SymbolKind.NamedType, x.Type.Kind);
Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug
Assert.Equal(SymbolKind.Parameter, x.Kind);
Assert.Equal(Accessibility.Private, m.DeclaredAccessibility);
}
[Fact]
public void NoParameterlessCtorForStruct()
{
var text = "struct A { A() {} }";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater.
// struct A { A() {} }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "A").WithArguments("parameterless struct constructors", "10.0").WithLocation(1, 12),
// (1,12): error CS8938: The parameterless struct constructor must be 'public'.
// struct A { A() {} }
Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "A").WithLocation(1, 12));
}
[WorkItem(537194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537194")]
[Fact]
public void DefaultCtor1()
{
Action<string, string, int, Accessibility?> check =
(source, className, ctorCount, accessibility) =>
{
var comp = CreateCompilation(source);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers(className, 0).Single();
var ctors = a.InstanceConstructors; // Note, this only returns *instance* constructors.
Assert.Equal(ctorCount, ctors.Length);
foreach (var ct in ctors)
{
Assert.Equal(
ct.IsStatic ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName,
ct.Name
);
if (accessibility != null)
Assert.Equal(accessibility, ct.DeclaredAccessibility);
}
};
Accessibility? doNotCheckAccessibility = null;
// A class without any defined constructors should generator a public constructor.
check(@"internal class A { }", "A", 1, Accessibility.Public);
// An abstract class without any defined constructors should generator a protected constructor.
check(@"abstract internal class A { }", "A", 1, Accessibility.Protected);
// A static class should not generate a default constructor
check(@"static internal class A { }", "A", 0, doNotCheckAccessibility);
// A class with a defined instance constructor should not generate a default constructor.
check(@"internal class A { A(int x) {} }", "A", 1, doNotCheckAccessibility);
// A class with only a static constructor defined should still generate a default instance constructor.
check(@"internal class A { static A(int x) {} }", "A", 1, doNotCheckAccessibility);
}
[WorkItem(537345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537345")]
[Fact]
public void Ctor1()
{
var text =
@"
class A {
A(int x) {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.InstanceConstructors.Single();
Assert.NotNull(m);
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m.Name);
Assert.True(m.ReturnsVoid);
Assert.Equal(MethodKind.Constructor, m.MethodKind);
var x = m.Parameters[0];
Assert.Equal("x", x.Name);
Assert.Equal(SymbolKind.NamedType, x.Type.Kind);
Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug
Assert.Equal(SymbolKind.Parameter, x.Kind);
Assert.Equal(Accessibility.Private, m.DeclaredAccessibility);
}
[Fact]
public void Simple2()
{
var text =
@"
class A {
void M<T>(int x) {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.NotNull(m);
Assert.True(m.ReturnsVoid);
Assert.Equal(MethodKind.Ordinary, m.MethodKind);
var x = m.Parameters[0];
Assert.Equal("x", x.Name);
Assert.Equal(SymbolKind.NamedType, x.Type.Kind);
Assert.Equal("Int32", x.Type.Name); // fully qualified to work around a metadata reader bug
Assert.Equal(SymbolKind.Parameter, x.Kind);
Assert.Equal(Accessibility.Private, m.DeclaredAccessibility);
}
[Fact]
public void Access1()
{
var text =
@"
class A {
void M1() {}
}
interface B {
void M2() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m1 = a.GetMembers("M1").Single() as MethodSymbol;
var b = global.GetTypeMembers("B", 0).Single();
var m2 = b.GetMembers("M2").Single() as MethodSymbol;
Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility);
Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility);
}
[Fact]
public void GenericParameter()
{
var text =
@"
public class MyList<T>
{
public void Add(T element)
{
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var mylist = global.GetTypeMembers("MyList", 1).Single();
var t1 = mylist.TypeParameters[0];
var add = mylist.GetMembers("Add").Single() as MethodSymbol;
var element = add.Parameters[0];
var t2 = element.Type;
Assert.Equal(t1, t2);
}
[Fact]
public void PartialLocation()
{
var text =
@"
public partial class A {
partial void M();
}
public partial class A {
partial void M() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M");
Assert.Equal(1, m.Length);
Assert.Equal(1, m.First().Locations.Length);
}
[Fact]
public void PartialExtractSyntaxLocation_DeclBeforeDef()
{
var text =
@"public partial class A {
partial void M();
}
public partial class A {
partial void M() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialDefinition());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).First();
var otherSymbol = m.PartialImplementationPart;
Assert.True(otherSymbol.IsPartialImplementation());
Assert.Equal(node, returnSyntax);
Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax());
}
[Fact]
public void PartialExtractSyntaxLocation_DefBeforeDecl()
{
var text =
@"public partial class A {
partial void M() {}
}
public partial class A {
partial void M();
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialDefinition());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Last();
var otherSymbol = m.PartialImplementationPart;
Assert.True(otherSymbol.IsPartialImplementation());
Assert.Equal(node, returnSyntax);
Assert.Equal(node, otherSymbol.ExtractReturnTypeSyntax());
}
[Fact]
public void PartialExtractSyntaxLocation_OnlyDef()
{
var text =
@"public partial class A {
partial void M() {}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialImplementation());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single().GetRoot();
var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single();
Assert.Equal(node, returnSyntax);
}
[Fact]
public void PartialExtractSyntaxLocation_OnlyDecl()
{
var text =
@"public partial class A {
partial void M();
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = (MethodSymbol)a.GetMembers("M").Single();
Assert.True(m.IsPartialDefinition());
var returnSyntax = m.ExtractReturnTypeSyntax();
var tree = comp.SyntaxTrees.Single().GetRoot();
var node = tree.DescendantNodes().OfType<PredefinedTypeSyntax>().Where(n => n.Keyword.Kind() == SyntaxKind.VoidKeyword).Single();
Assert.Equal(node, returnSyntax);
}
[Fact]
public void FullName()
{
var text =
@"
public class A {
public string M(int x);
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.Equal("System.String A.M(System.Int32 x)", m.ToTestDisplayString());
}
[Fact]
public void TypeParameterScope()
{
var text =
@"
public interface A {
T M<T>(T t);
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
var t = m.TypeParameters[0];
Assert.Equal(t, m.Parameters[0].Type);
Assert.Equal(t, m.ReturnType);
}
[WorkItem(931142, "DevDiv/Personal")]
[Fact]
public void RefOutParameterType()
{
var text = @"public class A {
void M(ref A refp, out long outp) { }
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
var p1 = m.Parameters[0];
var p2 = m.Parameters[1];
Assert.Equal(RefKind.Ref, p1.RefKind);
Assert.Equal(RefKind.Out, p2.RefKind);
var refP = p1.Type;
Assert.Equal(TypeKind.Class, refP.TypeKind);
Assert.True(refP.IsReferenceType);
Assert.False(refP.IsValueType);
Assert.Equal("Object", refP.BaseType().Name);
Assert.Equal(2, refP.GetMembers().Length); // M + generated constructor.
Assert.Equal(1, refP.GetMembers("M").Length);
var outP = p2.Type;
Assert.Equal(TypeKind.Struct, outP.TypeKind);
Assert.False(outP.IsReferenceType);
Assert.True(outP.IsValueType);
Assert.False(outP.IsStatic);
Assert.False(outP.IsAbstract);
Assert.True(outP.IsSealed);
Assert.Equal(Accessibility.Public, outP.DeclaredAccessibility);
Assert.Equal(5, outP.Interfaces().Length);
Assert.Equal(0, outP.GetTypeMembers().Length); // Enumerable.Empty<NamedTypeSymbol>()
Assert.Equal(0, outP.GetTypeMembers(String.Empty).Length);
Assert.Equal(0, outP.GetTypeMembers(String.Empty, 0).Length);
}
[Fact]
public void RefReturn()
{
var text =
@"public class A
{
ref int M(ref int i)
{
return ref i;
}
}
";
var comp = CreateCompilationWithMscorlib45(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var m = a.GetMembers("M").Single() as MethodSymbol;
Assert.Equal(RefKind.Ref, m.RefKind);
Assert.Equal(TypeKind.Struct, m.ReturnType.TypeKind);
Assert.False(m.ReturnType.IsReferenceType);
Assert.True(m.ReturnType.IsValueType);
var p1 = m.Parameters[0];
Assert.Equal(RefKind.Ref, p1.RefKind);
Assert.Equal("ref System.Int32 A.M(ref System.Int32 i)", m.ToTestDisplayString());
}
[Fact]
public void BothKindsOfCtors()
{
var text =
@"public class Test
{
public Test() {}
public static Test() {}
}";
var comp = CreateCompilation(text);
var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single();
var members = classTest.GetMembers();
Assert.Equal(2, members.Length);
}
[WorkItem(931663, "DevDiv/Personal")]
[Fact]
public void RefOutArrayParameter()
{
var text =
@"public class Test
{
public void MethodWithRefOutArray(ref int[] ary1, out string[] ary2)
{
ary2 = null;
}
}";
var comp = CreateCompilation(text);
var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single();
var method = classTest.GetMembers("MethodWithRefOutArray").Single() as MethodSymbol;
Assert.Equal(classTest, method.ContainingSymbol);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.True(method.IsDefinition);
// var paramList = (method as MethodSymbol).Parameters;
var p1 = method.Parameters[0];
var p2 = method.Parameters[1];
Assert.Equal(RefKind.Ref, p1.RefKind);
Assert.Equal(RefKind.Out, p2.RefKind);
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void InterfaceImplementsCrossTrees(string ob, string cb)
{
var text1 =
@"using System;
using System.Collections.Generic;
namespace NS
" + ob + @"
public class Abc {}
public interface IGoo<T>
{
void M(ref T t);
}
public interface I1
{
void M(ref string p);
int M1(short p1, params object[] ary);
}
public interface I2 : I1
{
void M21();
Abc M22(ref Abc p);
}
" + cb;
var text2 =
@"using System;
using System.Collections.Generic;
namespace NS.NS1
" + ob + @"
public class Impl : I2, IGoo<string>, I1
{
void IGoo<string>.M(ref string p) { }
void I1.M(ref string p) { }
public int M1(short p1, params object[] ary) { return p1; }
public void M21() {}
public Abc M22(ref Abc p) { return p; }
}
struct S<T>: IGoo<T>
{
void IGoo<T>.M(ref T t) {}
}
" + cb;
var comp = CreateCompilation(new[] { text1, text2 });
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var ns1 = ns.GetMembers("NS1").Single() as NamespaceSymbol;
var classImpl = ns1.GetTypeMembers("Impl", 0).Single() as NamedTypeSymbol;
Assert.Equal(3, classImpl.Interfaces().Length);
//
var itfc = classImpl.Interfaces().First() as NamedTypeSymbol;
Assert.Equal(1, itfc.Interfaces().Length);
itfc = itfc.Interfaces().First() as NamedTypeSymbol;
Assert.Equal("I1", itfc.Name);
// explicit interface member names include the explicit interface
var mems = classImpl.GetMembers("M");
Assert.Equal(0, mems.Length);
//var mem1 = mems.First() as MethodSymbol;
// not impl
// Assert.Equal(MethodKind.ExplicitInterfaceImplementation, mem1.MethodKind);
// Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count());
var mem1 = classImpl.GetMembers("M22").Single() as MethodSymbol;
// not impl
// Assert.Equal(0, mem1.ExplicitInterfaceImplementation.Count());
var param = mem1.Parameters.First() as ParameterSymbol;
Assert.Equal(RefKind.Ref, param.RefKind);
Assert.Equal("ref NS.Abc p", param.ToTestDisplayString());
var structImpl = ns1.GetTypeMembers("S").Single() as NamedTypeSymbol;
Assert.Equal(1, structImpl.Interfaces().Length);
itfc = structImpl.Interfaces().First() as NamedTypeSymbol;
Assert.Equal("NS.IGoo<T>", itfc.ToTestDisplayString());
//var mem2 = structImpl.GetMembers("M").Single() as MethodSymbol;
// not impl
// Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count());
}
[Fact]
public void AbstractVirtualMethodsCrossTrees()
{
var text = @"
namespace MT {
public interface IGoo {
void M0();
}
}
";
var text1 = @"
namespace N1 {
using MT;
public abstract class Abc : IGoo {
public abstract void M0();
public char M1;
public abstract object M2(ref object p1);
public virtual void M3(ulong p1, out ulong p2) { p2 = p1; }
public virtual object M4(params object[] ary) { return null; }
public static void M5<T>(T t) { }
public abstract ref int M6(ref int i);
}
}
";
var text2 = @"
namespace N1.N2 {
public class Bbc : Abc {
public override void M0() { }
public override object M2(ref object p1) { M1 = 'a'; return p1; }
public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; }
public override object M4(params object[] ary) { return null; }
public static new void M5<T>(T t) { }
public override ref int M6(ref int i) { return ref i; }
}
}
";
var comp = CreateCompilationWithMscorlib45(new[] { text, text1, text2 });
Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol;
var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol;
#region "Bbc"
var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol;
var mems = type1.GetMembers();
Assert.Equal(7, mems.Length);
// var sorted = mems.Orderby(m => m.Name).ToArray();
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.False(m0.IsAbstract);
Assert.False(m0.IsOverride);
Assert.False(m0.IsSealed);
Assert.False(m0.IsVirtual);
var m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.False(m1.IsAbstract);
Assert.True(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
var m2 = sorted[2] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.False(m2.IsAbstract);
Assert.True(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
var m3 = sorted[3] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.True(m3.IsOverride);
Assert.True(m3.IsSealed);
Assert.False(m3.IsVirtual);
var m4 = sorted[4] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.True(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.False(m4.IsVirtual);
var m5 = sorted[5] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
var m6 = sorted[6] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.False(m6.IsAbstract);
Assert.True(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
#region "Abc"
var type2 = type1.BaseType();
Assert.Equal("Abc", type2.Name);
mems = type2.GetMembers();
Assert.Equal(8, mems.Length);
sorted = (from m in mems
orderby m.Name
select m).ToArray();
var mm = sorted[2] as FieldSymbol;
Assert.Equal("M1", mm.Name);
Assert.False(mm.IsAbstract);
Assert.False(mm.IsOverride);
Assert.False(mm.IsSealed);
Assert.False(mm.IsVirtual);
m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.Equal(Accessibility.Protected, m0.DeclaredAccessibility);
m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.True(m1.IsAbstract);
Assert.False(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
m2 = sorted[3] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.True(m2.IsAbstract);
Assert.False(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
m3 = sorted[4] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.False(m3.IsOverride);
Assert.False(m3.IsSealed);
Assert.True(m3.IsVirtual);
m4 = sorted[5] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.False(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.True(m4.IsVirtual);
m5 = sorted[6] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
m6 = sorted[7] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.True(m6.IsAbstract);
Assert.False(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
}
[WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")]
[Fact]
public void AbstractVirtualMethodsCrossComps()
{
var text = @"
namespace MT {
public interface IGoo {
void M0();
}
}
";
var text1 = @"
namespace N1 {
using MT;
public abstract class Abc : IGoo {
public abstract void M0();
public char M1;
public abstract object M2(ref object p1);
public virtual void M3(ulong p1, out ulong p2) { p2 = p1; }
public virtual object M4(params object[] ary) { return null; }
public static void M5<T>(T t) { }
public abstract ref int M6(ref int i);
}
}
";
var text2 = @"
namespace N1.N2 {
public class Bbc : Abc {
public override void M0() { }
public override object M2(ref object p1) { M1 = 'a'; return p1; }
public sealed override void M3(ulong p1, out ulong p2) { p2 = p1; }
public override object M4(params object[] ary) { return null; }
public static new void M5<T>(T t) { }
public override ref int M6(ref int i) { return ref i; }
}
}
";
var comp1 = CreateCompilationWithMscorlib45(text);
var compRef1 = new CSharpCompilationReference(comp1);
var comp2 = CreateCompilationWithMscorlib45(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2");
//Compilation.Create(outputName: "Test2", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) },
// references: new MetadataReference[] { compRef1, GetCorlibReference() });
var compRef2 = new CSharpCompilationReference(comp2);
var comp = CreateCompilationWithMscorlib45(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3");
//Compilation.Create(outputName: "Test3", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) },
// references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() });
Assert.Equal(0, comp1.GetDiagnostics().Count());
Assert.Equal(0, comp2.GetDiagnostics().Count());
Assert.Equal(0, comp.GetDiagnostics().Count());
//string errs = String.Empty;
//foreach (var e in comp.GetDiagnostics())
//{
// errs += e.Info.ToString() + "\r\n";
//}
//Assert.Equal("Errs", errs);
var ns = comp.GlobalNamespace.GetMembers("N1").Single() as NamespaceSymbol;
var ns1 = ns.GetMembers("N2").Single() as NamespaceSymbol;
#region "Bbc"
var type1 = ns1.GetTypeMembers("Bbc", 0).Single() as NamedTypeSymbol;
var mems = type1.GetMembers();
Assert.Equal(7, mems.Length);
// var sorted = mems.Orderby(m => m.Name).ToArray();
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.False(m0.IsAbstract);
Assert.False(m0.IsOverride);
Assert.False(m0.IsSealed);
Assert.False(m0.IsVirtual);
var m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.False(m1.IsAbstract);
Assert.True(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
var m2 = sorted[2] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.False(m2.IsAbstract);
Assert.True(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
var m3 = sorted[3] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.True(m3.IsOverride);
Assert.True(m3.IsSealed);
Assert.False(m3.IsVirtual);
var m4 = sorted[4] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.True(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.False(m4.IsVirtual);
var m5 = sorted[5] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
var m6 = sorted[6] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.False(m6.IsAbstract);
Assert.True(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
#region "Abc"
var type2 = type1.BaseType();
Assert.Equal("Abc", type2.Name);
mems = type2.GetMembers();
Assert.Equal(8, mems.Length);
sorted = (from m in mems
orderby m.Name
select m).ToArray();
var mm = sorted[2] as FieldSymbol;
Assert.Equal("M1", mm.Name);
Assert.False(mm.IsAbstract);
Assert.False(mm.IsOverride);
Assert.False(mm.IsSealed);
Assert.False(mm.IsVirtual);
m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.False(m0.IsAbstract);
Assert.False(m0.IsOverride);
Assert.False(m0.IsSealed);
Assert.False(m0.IsVirtual);
m1 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m1.Name);
Assert.True(m1.IsAbstract);
Assert.False(m1.IsOverride);
Assert.False(m1.IsSealed);
Assert.False(m1.IsVirtual);
m2 = sorted[3] as MethodSymbol;
Assert.Equal("M2", m2.Name);
Assert.True(m2.IsAbstract);
Assert.False(m2.IsOverride);
Assert.False(m2.IsSealed);
Assert.False(m2.IsVirtual);
m3 = sorted[4] as MethodSymbol;
Assert.Equal("M3", m3.Name);
Assert.False(m3.IsAbstract);
Assert.False(m3.IsOverride);
Assert.False(m3.IsSealed);
Assert.True(m3.IsVirtual);
m4 = sorted[5] as MethodSymbol;
Assert.Equal("M4", m4.Name);
Assert.False(m4.IsAbstract);
Assert.False(m4.IsOverride);
Assert.False(m4.IsSealed);
Assert.True(m4.IsVirtual);
m5 = sorted[6] as MethodSymbol;
Assert.Equal("M5", m5.Name);
Assert.False(m5.IsAbstract);
Assert.False(m5.IsOverride);
Assert.False(m5.IsSealed);
Assert.False(m5.IsVirtual);
Assert.True(m5.IsStatic);
m6 = sorted[7] as MethodSymbol;
Assert.Equal("M6", m6.Name);
Assert.True(m6.IsAbstract);
Assert.False(m6.IsOverride);
Assert.False(m6.IsSealed);
Assert.False(m6.IsVirtual);
#endregion
}
[Fact]
public void OverloadMethodsCrossTrees()
{
var text = @"
using System;
namespace NS
{
public class A
{
public void Overloads(ushort p) { }
public void Overloads(A p) { }
}
}
";
var text1 = @"
namespace NS
{
using System;
public class B : A
{
public void Overloads(ref A p) { }
public string Overloads(B p) { return null; }
protected long Overloads(A p, long p2) { return p2; }
}
}
";
var text2 = @"
namespace NS {
public class Test {
public class C : B {
protected long Overloads(A p, B p2) { return 1; }
}
public static void Main() {
var obj = new C();
A a = obj;
obj.Overloads(ref a);
obj.Overloads(obj);
}
}
}
";
var comp = CreateCompilation(new[] { text, text1, text2 });
// Not impl errors
// Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
var mems = type1.GetMembers();
Assert.Equal(2, mems.Length);
var mems1 = type1.BaseType().GetMembers();
Assert.Equal(4, mems1.Length);
var mems2 = type1.BaseType().BaseType().GetMembers();
Assert.Equal(3, mems2.Length);
var list = new List<Symbol>();
list.AddRange(mems);
list.AddRange(mems1);
list.AddRange(mems2);
var sorted = (from m in list
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[1] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[2] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
var m1 = sorted[3] as MethodSymbol;
Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString());
m1 = sorted[4] as MethodSymbol;
Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString());
m1 = sorted[5] as MethodSymbol;
Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString());
m1 = sorted[6] as MethodSymbol;
Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString());
m1 = sorted[7] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString());
m1 = sorted[8] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString());
}
[WorkItem(537752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537752")]
[Fact]
public void OverloadMethodsCrossComps()
{
var text = @"
namespace NS
{
public class A
{
public void Overloads(ushort p) { }
public void Overloads(A p) { }
}
}
";
var text1 = @"
namespace NS
{
public class B : A
{
public void Overloads(ref A p) { }
public string Overloads(B p) { return null; }
protected long Overloads(A p, long p2) { return p2; }
}
}
";
var text2 = @"
namespace NS {
public class Test {
public class C : B {
protected long Overloads(A p, B p2) { return 1; }
}
public static void Main() {
C obj = new C(); // var NotImpl ???
A a = obj;
obj.Overloads(ref a);
obj.Overloads(obj);
}
}
}
";
var comp1 = CreateCompilation(text);
var compRef1 = new CSharpCompilationReference(comp1);
var comp2 = CreateCompilation(new string[] { text1 }, new List<MetadataReference>() { compRef1 }, assemblyName: "Test2");
//Compilation.Create(outputName: "Test2", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text1) },
// references: new MetadataReference[] { compRef1, GetCorlibReference() });
var compRef2 = new CSharpCompilationReference(comp2);
var comp = CreateCompilation(new string[] { text2 }, new List<MetadataReference>() { compRef1, compRef2 }, assemblyName: "Test3");
//Compilation.Create(outputName: "Test3", options: CompilationOptions.Default,
// syntaxTrees: new SyntaxTree[] { SyntaxTree.ParseCompilationUnit(text2) },
// references: new MetadataReference[] { compRef1, compRef2, GetCorlibReference() });
Assert.Equal(0, comp1.GetDiagnostics().Count());
Assert.Equal(0, comp2.GetDiagnostics().Count());
Assert.Equal(0, comp.GetDiagnostics().Count());
//string errs = String.Empty;
//foreach (var e in comp.GetDiagnostics())
//{
// errs += e.Info.ToString() + "\r\n";
//}
//Assert.Equal(String.Empty, errs);
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = (ns.GetTypeMembers("Test").Single() as NamedTypeSymbol).GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
var mems = type1.GetMembers();
Assert.Equal(2, mems.Length);
var mems1 = type1.BaseType().GetMembers();
Assert.Equal(4, mems1.Length);
var mems2 = type1.BaseType().BaseType().GetMembers();
Assert.Equal(3, mems2.Length);
var list = new List<Symbol>();
list.AddRange(mems);
list.AddRange(mems1);
list.AddRange(mems2);
var sorted = (from m in list
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[1] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
m0 = sorted[2] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
var m1 = sorted[3] as MethodSymbol;
Assert.Equal("System.Int64 NS.Test.C.Overloads(NS.A p, NS.B p2)", m1.ToTestDisplayString());
m1 = sorted[4] as MethodSymbol;
Assert.Equal("void NS.B.Overloads(ref NS.A p)", m1.ToTestDisplayString());
m1 = sorted[5] as MethodSymbol;
Assert.Equal("System.String NS.B.Overloads(NS.B p)", m1.ToTestDisplayString());
m1 = sorted[6] as MethodSymbol;
Assert.Equal("System.Int64 NS.B.Overloads(NS.A p, System.Int64 p2)", m1.ToTestDisplayString());
m1 = sorted[7] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(System.UInt16 p)", m1.ToTestDisplayString());
m1 = sorted[8] as MethodSymbol;
Assert.Equal("void NS.A.Overloads(NS.A p)", m1.ToTestDisplayString());
}
[WorkItem(537754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537754")]
[Fact]
public void PartialMethodsCrossTrees()
{
var text = @"
namespace NS
{
public partial struct PS
{
partial void M0(string p);
partial class GPC<T>
{
partial void GM0(T p1, short p2);
}
}
}
";
var text1 = @"
namespace NS
{
partial struct PS
{
partial void M0(string p) { }
partial void M1(params ulong[] ary);
public partial class GPC<T>
{
partial void GM0(T p1, short p2) { }
partial void GM1<V>(T p1, V p2);
}
}
}
";
var text2 = @"
namespace NS
{
partial struct PS
{
partial void M1(params ulong[] ary) {}
partial void M2(sbyte p);
partial class GPC<T>
{
partial void GM1<V>(T p1, V p2) { }
}
}
}
";
var comp = CreateCompilation(new[] { text, text1, text2 });
Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("PS", 0).Single() as NamedTypeSymbol;
// Bug
// Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
Assert.Equal(3, type1.Locations.Length);
Assert.False(type1.IsReferenceType);
Assert.True(type1.IsValueType);
var mems = type1.GetMembers();
Assert.Equal(5, mems.Length);
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility);
Assert.Equal(3, m0.Locations.Length);
var m2 = sorted[2] as MethodSymbol;
Assert.Equal("M0", m2.Name);
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility);
Assert.Equal(1, m2.Locations.Length);
Assert.True(m2.ReturnsVoid);
var m3 = sorted[3] as MethodSymbol;
Assert.Equal("M1", m3.Name);
Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility);
Assert.Equal(1, m3.Locations.Length);
var m4 = sorted[4] as MethodSymbol;
Assert.Equal("M2", m4.Name);
Assert.Equal(Accessibility.Private, m4.DeclaredAccessibility);
Assert.Equal(1, m4.Locations.Length);
#region "GPC"
var type2 = sorted[1] as NamedTypeSymbol;
Assert.Equal("NS.PS.GPC<T>", type2.ToTestDisplayString());
Assert.True(type2.IsNestedType());
// Bug
Assert.Equal(Accessibility.Public, type2.DeclaredAccessibility);
Assert.Equal(3, type2.Locations.Length);
Assert.False(type2.IsValueType);
Assert.True(type2.IsReferenceType);
mems = type2.GetMembers();
// Assert.Equal(3, mems.Count());
sorted = (from m in mems
orderby m.Name
select m).ToArray();
m0 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m0.Name);
Assert.Equal(Accessibility.Public, m0.DeclaredAccessibility);
Assert.Equal(3, m0.Locations.Length);
var mm = sorted[1] as MethodSymbol;
Assert.Equal("GM0", mm.Name);
Assert.Equal(Accessibility.Private, mm.DeclaredAccessibility);
Assert.Equal(1, mm.Locations.Length);
m2 = sorted[2] as MethodSymbol;
Assert.Equal("GM1", m2.Name);
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility);
Assert.Equal(1, m2.Locations.Length);
Assert.True(m2.ReturnsVoid);
#endregion
}
[WorkItem(537755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537755")]
[Fact]
public void PartialMethodsWithRefParams()
{
var text = @"
namespace NS
{
public partial class PC
{
partial void M0(ref long p);
partial void M1(ref string p);
}
partial class PC
{
partial void M0(ref long p) {}
partial void M1(ref string p) {}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("PC", 0).Single() as NamedTypeSymbol;
Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility);
Assert.Equal(2, type1.Locations.Length);
Assert.True(type1.IsReferenceType);
Assert.False(type1.IsValueType);
var mems = type1.GetMembers();
// Bug: actual 5
Assert.Equal(3, mems.Length);
var sorted = (from m in mems
orderby m.Name
select m).ToArray();
var m1 = sorted[0] as MethodSymbol;
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, m1.Name);
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility);
Assert.Equal(2, m1.Locations.Length);
var m2 = sorted[1] as MethodSymbol;
Assert.Equal("M0", m2.Name);
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility);
Assert.Equal(1, m2.Locations.Length);
Assert.True(m2.ReturnsVoid);
var m3 = sorted[2] as MethodSymbol;
Assert.Equal("M1", m3.Name);
Assert.Equal(Accessibility.Private, m3.DeclaredAccessibility);
Assert.Equal(1, m3.Locations.Length);
Assert.True(m3.ReturnsVoid);
}
[WorkItem(2358, "DevDiv_Projects/Roslyn")]
[Fact]
public void ExplicitInterfaceImplementation()
{
var text = @"
interface ISubFuncProp
{
}
interface Interface3
{
System.Collections.Generic.List<ISubFuncProp> Goo();
}
interface Interface3Derived : Interface3
{
}
public class DerivedClass : Interface3Derived
{
System.Collections.Generic.List<ISubFuncProp> Interface3.Goo()
{
return null;
}
System.Collections.Generic.List<ISubFuncProp> Goo()
{
return null;
}
}";
var comp = CreateCompilation(text);
var derivedClass = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("DerivedClass")[0];
var members = derivedClass.GetMembers();
Assert.Equal(3, members.Length);
}
[Fact]
public void SubstitutedExplicitInterfaceImplementation()
{
var text = @"
public class A<T>
{
public interface I<U>
{
void M<V>(T t, U u, V v);
}
}
public class B<Q, R> : A<Q>.I<R>
{
void A<Q>.I<R>.M<S>(Q q, R r, S s) { }
}
public class C : B<int, long>
{
}";
var comp = CreateCompilation(text);
var classB = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("B").Single();
var classBTypeArguments = classB.TypeArguments();
Assert.Equal(2, classBTypeArguments.Length);
Assert.Equal("Q", classBTypeArguments[0].Name);
Assert.Equal("R", classBTypeArguments[1].Name);
var classBMethodM = (MethodSymbol)classB.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal));
var classBMethodMTypeParameters = classBMethodM.TypeParameters;
Assert.Equal(1, classBMethodMTypeParameters.Length);
Assert.Equal("S", classBMethodMTypeParameters[0].Name);
var classBMethodMParameters = classBMethodM.Parameters;
Assert.Equal(3, classBMethodMParameters.Length);
Assert.Equal(classBTypeArguments[0], classBMethodMParameters[0].Type);
Assert.Equal(classBTypeArguments[1], classBMethodMParameters[1].Type);
Assert.Equal(classBMethodMTypeParameters[0], classBMethodMParameters[2].Type);
var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").Single();
var classCBase = classC.BaseType();
Assert.Equal(classB, classCBase.ConstructedFrom);
var classCBaseTypeArguments = classCBase.TypeArguments();
Assert.Equal(2, classCBaseTypeArguments.Length);
Assert.Equal(SpecialType.System_Int32, classCBaseTypeArguments[0].SpecialType);
Assert.Equal(SpecialType.System_Int64, classCBaseTypeArguments[1].SpecialType);
var classCBaseMethodM = (MethodSymbol)classCBase.GetMembers().Single(sym => sym.Name.EndsWith("M", StringComparison.Ordinal));
Assert.NotEqual(classBMethodM, classCBaseMethodM);
var classCBaseMethodMTypeParameters = classCBaseMethodM.TypeParameters;
Assert.Equal(1, classCBaseMethodMTypeParameters.Length);
Assert.Equal("S", classCBaseMethodMTypeParameters[0].Name);
var classCBaseMethodMParameters = classCBaseMethodM.Parameters;
Assert.Equal(3, classCBaseMethodMParameters.Length);
Assert.Equal(classCBaseTypeArguments[0], classCBaseMethodMParameters[0].Type);
Assert.Equal(classCBaseTypeArguments[1], classCBaseMethodMParameters[1].Type);
Assert.Equal(classCBaseMethodMTypeParameters[0], classCBaseMethodMParameters[2].Type);
}
#region Regressions
[WorkItem(527149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527149")]
[Fact]
public void MethodWithParamsInParameters()
{
var text =
@"class C
{
void F1(params int[] a) { }
}
";
var comp = CreateEmptyCompilation(text);
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var f1 = c.GetMembers("F1").Single() as MethodSymbol;
Assert.Equal("void C.F1(params System.Int32[missing][] a)", f1.ToTestDisplayString());
}
[WorkItem(537352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537352")]
[Fact]
public void Arglist()
{
string code = @"
class AA
{
public static int Method1(__arglist)
{
}
}";
var comp = CreateCompilation(code);
NamedTypeSymbol nts = comp.Assembly.GlobalNamespace.GetTypeMembers()[0];
Assert.Equal("AA", nts.ToTestDisplayString());
Assert.Empty(comp.GetDeclarationDiagnostics());
Assert.Equal("System.Int32 AA.Method1(__arglist)", nts.GetMembers("Method1").Single().ToTestDisplayString());
}
[WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")]
[Fact]
public void ExpImpInterfaceWithGlobal()
{
var text = @"
using System;
namespace N1
{
interface I1
{
int Method();
}
}
namespace N2
{
class ExpImpl : N1.I1
{
int global::N1.I1.Method()
{
return 42;
}
ExpImpl(){}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
var ns = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("ExpImpl", 0).Single() as NamedTypeSymbol;
var m1 = type1.GetMembers().FirstOrDefault() as MethodSymbol;
Assert.Equal("System.Int32 N2.ExpImpl.N1.I1.Method()", m1.ToTestDisplayString());
var em1 = m1.ExplicitInterfaceImplementations.First() as MethodSymbol;
Assert.Equal("System.Int32 N1.I1.Method()", em1.ToTestDisplayString());
}
[WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")]
[Fact]
public void BaseInterfaceNameWithAlias()
{
var text = @"
using N1Alias = N1;
namespace N1
{
interface I1 {}
}
namespace N2
{
class N1Alias {}
class Test : N1Alias::I1
{
static int Main()
{
Test t = new Test();
return 0;
}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
var n2 = comp.GlobalNamespace.GetMembers("N2").Single() as NamespaceSymbol;
var test = n2.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var bt = test.Interfaces().Single() as NamedTypeSymbol;
Assert.Equal("N1.I1", bt.ToTestDisplayString());
}
[WorkItem(538209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538209")]
[Fact]
public void ParameterAccessibility01()
{
var text = @"
using System;
class MyClass
{
private class MyInner
{
public int MyMeth(MyInner2 arg)
{
return arg.intI;
}
}
protected class MyInner2
{
public int intI = 2;
}
public static int Main()
{
MyInner MI = new MyInner();
if (MI.MyMeth(new MyInner2()) == 2)
{
return 0;
}
else
{
return 1;
}
}
}
";
var comp = CreateCompilation(text);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
}
[WorkItem(537877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537877")]
[Fact]
public void MethodsWithSameSigDiffReturnType()
{
var text = @"
class Test
{
public int M1()
{
}
float M1()
{
}
}
";
var comp = CreateCompilation(text);
var test = comp.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var members = test.GetMembers("M1");
Assert.Equal(2, members.Length);
Assert.Equal("System.Int32 Test.M1()", members[0].ToTestDisplayString());
Assert.Equal("System.Single Test.M1()", members[1].ToTestDisplayString());
}
[Fact]
public void OverriddenMethod01()
{
var text = @"
class A
{
public virtual void F(object[] args) {}
}
class B : A
{
public override void F(params object[] args) {}
public static void Main(B b)
{
b.F(// yes, there is a parse error here
}
}
";
var comp = CreateCompilation(text);
var a = comp.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol;
var b = comp.GlobalNamespace.GetTypeMembers("B").Single() as NamedTypeSymbol;
var f = b.GetMembers("F").Single() as MethodSymbol;
Assert.True(f.IsOverride);
var f2 = f.OverriddenMethod;
Assert.NotNull(f2);
Assert.Equal("A", f2.ContainingSymbol.Name);
}
#endregion
[WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
[Fact]
public void MethodEscapedIdentifier()
{
var text = @"
interface @void { @void @return(@void @in); };
class @int { virtual @int @float(@int @in); };
class C1 : @int, @void
{
@void @void.@return(@void @in) { return null; }
override @int @float(@int @in) { return null; }
}
";
var comp = CreateCompilation(Parse(text));
NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single();
// Per explanation from NGafter:
//
// We intentionally escape keywords that appear in the type qualification of the interface name
// on interface implementation members. That is necessary to distinguish I<int>.F from I<@int>.F,
// for example, which might both be members in a class. An alternative would be to stop using the
// abbreviated names for the built-in types, but since we may want to use these names in
// diagnostics the @-escaped version is preferred.
//
MethodSymbol mreturn = (MethodSymbol)c1.GetMembers("@void.return").Single();
Assert.Equal("@void.return", mreturn.Name);
Assert.Equal("C1.@void.@return(@void)", mreturn.ToString());
NamedTypeSymbol rvoid = (NamedTypeSymbol)mreturn.ReturnType;
Assert.Equal("void", rvoid.Name);
Assert.Equal("@void", rvoid.ToString());
MethodSymbol mvoidreturn = (MethodSymbol)mreturn.ExplicitInterfaceImplementations.Single();
Assert.Equal("return", mvoidreturn.Name);
Assert.Equal("@void.@return(@void)", mvoidreturn.ToString());
ParameterSymbol pin = mreturn.Parameters.Single();
Assert.Equal("in", pin.Name);
Assert.Equal("@in", pin.ToDisplayString(
new SymbolDisplayFormat(
parameterOptions: SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)));
MethodSymbol mfloat = (MethodSymbol)c1.GetMembers("float").Single();
Assert.Equal("float", mfloat.Name);
Assert.Empty(c1.GetMembers("@float"));
}
[Fact]
public void ExplicitInterfaceImplementationSimple()
{
string text = @"
interface I
{
void Method();
}
class C : I
{
void I.Method() { }
}
";
var comp = CreateCompilation(Parse(text));
var globalNamespace = comp.GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, explicitImpl);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[Fact]
public void ExplicitInterfaceImplementationCorLib()
{
string text = @"
class F : System.IFormattable
{
string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider)
{
return null;
}
}
";
var comp = CreateCompilation(Parse(text));
var globalNamespace = comp.GlobalNamespace;
var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("System").Single();
var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("IFormattable").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("ToString").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("F").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classMethod = (MethodSymbol)@class.GetMembers("System.IFormattable.ToString").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, explicitImpl);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[Fact]
public void ExplicitInterfaceImplementationRef()
{
string text = @"
interface I
{
ref int Method(ref int i);
}
class C : I
{
ref int I.Method(ref int i) { return ref i; }
}
";
var comp = CreateCompilationWithMscorlib45(text);
var globalNamespace = comp.GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
Assert.Equal(RefKind.Ref, interfaceMethod.RefKind);
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
Assert.Equal(RefKind.Ref, classMethod.RefKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceMethod, explicitImpl);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[Fact]
public void ExplicitInterfaceImplementationGeneric()
{
string text = @"
namespace Namespace
{
interface I<T>
{
void Method(T t);
}
}
class IC : Namespace.I<int>
{
void Namespace.I<int>.Method(int i) { }
}
";
var comp = CreateCompilation(Parse(text));
var globalNamespace = comp.GlobalNamespace;
var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("Namespace").Single();
var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("I", 1).Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IC").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Single();
var classMethod = (MethodSymbol)@class.GetMembers("Namespace.I<System.Int32>.Method").Single();
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterface, explicitImpl.ContainingType);
Assert.Equal(substitutedInterfaceMethod.OriginalDefinition, explicitImpl.OriginalDefinition);
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(@class, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(classMethod, explicitOverride.ImplementingMethod.GetInternalSymbol());
var explicitOverrideImplementedMethod = explicitOverride.ImplementedMethod;
Assert.Equal(substitutedInterface, explicitOverrideImplementedMethod.GetContainingType(context).GetInternalSymbol());
Assert.Equal(substitutedInterfaceMethod.Name, explicitOverrideImplementedMethod.Name);
Assert.Equal(substitutedInterfaceMethod.Arity, explicitOverrideImplementedMethod.GenericParameterCount);
context.Diagnostics.Verify();
}
[Fact()]
public void TestMetadataVirtual()
{
string text = @"
class C
{
virtual void Method1() { }
virtual void Method2() { }
void Method3() { }
void Method4() { }
}
";
var comp = CreateCompilation(Parse(text));
var @class = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single();
var method1 = (SourceMemberMethodSymbol)@class.GetMembers("Method1").Single();
var method2 = (SourceMemberMethodSymbol)@class.GetMembers("Method2").Single();
var method3 = (SourceMemberMethodSymbol)@class.GetMembers("Method3").Single();
var method4 = (SourceMemberMethodSymbol)@class.GetMembers("Method4").Single();
Assert.True(method1.IsVirtual);
Assert.True(method2.IsVirtual);
Assert.False(method3.IsVirtual);
Assert.False(method4.IsVirtual);
//1 and 3 - read before set
Assert.True(((Cci.IMethodDefinition)method1.GetCciAdapter()).IsVirtual);
Assert.False(((Cci.IMethodDefinition)method3.GetCciAdapter()).IsVirtual);
//2 and 4 - set before read
method2.EnsureMetadataVirtual();
method4.EnsureMetadataVirtual();
//can set twice (e.g. if the method implicitly implements more than one interface method)
method2.EnsureMetadataVirtual();
method4.EnsureMetadataVirtual();
Assert.True(((Cci.IMethodDefinition)method2.GetCciAdapter()).IsVirtual);
Assert.True(((Cci.IMethodDefinition)method4.GetCciAdapter()).IsVirtual);
//API view unchanged
Assert.True(method1.IsVirtual);
Assert.True(method2.IsVirtual);
Assert.False(method3.IsVirtual);
Assert.False(method4.IsVirtual);
}
[Fact]
public void ExplicitStaticConstructor()
{
string text = @"
class C
{
static C() { }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName);
Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind);
Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility);
Assert.True(staticConstructor.IsStatic, "Static constructor should be static");
Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType);
}
[Fact]
public void ImplicitStaticConstructor()
{
string text = @"
class C
{
static int f = 1; //initialized in implicit static constructor
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (4,16): warning CS0414: The field 'C.f' is assigned but its value is never used
// static int f = 1; //initialized in implicit static constructor
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f")
);
var staticConstructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.StaticConstructorName);
Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind);
Assert.Equal(Accessibility.Private, staticConstructor.DeclaredAccessibility);
Assert.True(staticConstructor.IsStatic, "Static constructor should be static");
Assert.Equal(SpecialType.System_Void, staticConstructor.ReturnType.SpecialType);
}
[WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")]
[Fact]
public void AccessorMethodAccessorOverriding()
{
var text = @"
public class A
{
public virtual int P { get; set; }
}
public class B : A
{
public virtual int get_P() { return 0; }
}
public class C : B
{
public override int P { get; set; }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var globalNamespace = comp.GlobalNamespace;
var classA = globalNamespace.GetMember<NamedTypeSymbol>("A");
var classB = globalNamespace.GetMember<NamedTypeSymbol>("B");
var classC = globalNamespace.GetMember<NamedTypeSymbol>("C");
var methodA = classA.GetMember<PropertySymbol>("P").GetMethod;
var methodB = classB.GetMember<MethodSymbol>("get_P");
var methodC = classC.GetMember<PropertySymbol>("P").GetMethod;
var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")]
[Fact]
public void MethodAccessorMethodOverriding()
{
var text = @"
public class A
{
public virtual int get_P() { return 0; }
}
public class B : A
{
public virtual int P { get; set; }
}
public class C : B
{
public override int get_P() { return 0; }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var globalNamespace = comp.GlobalNamespace;
var classA = globalNamespace.GetMember<NamedTypeSymbol>("A");
var classB = globalNamespace.GetMember<NamedTypeSymbol>("B");
var classC = globalNamespace.GetMember<NamedTypeSymbol>("C");
var methodA = classA.GetMember<MethodSymbol>("get_P");
var methodB = classB.GetMember<PropertySymbol>("P").GetMethod;
var methodC = classC.GetMember<MethodSymbol>("get_P");
var typeDefC = (Cci.ITypeDefinition)classC.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single();
Assert.Equal(classC, explicitOverride.ContainingType.GetInternalSymbol());
Assert.Equal(methodC, explicitOverride.ImplementingMethod.GetInternalSymbol());
Assert.Equal(methodA, explicitOverride.ImplementedMethod.GetInternalSymbol());
context.Diagnostics.Verify();
}
[WorkItem(543444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543444")]
[Fact]
public void BadArityInOperatorDeclaration()
{
var text =
@"class A
{
public static bool operator true(A x, A y) { return false; }
}
class B
{
public static B operator *(B x) { return null; }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (3,33): error CS1020: Overloadable binary operator expected
// public static bool operator true(A x, A y) { return false; }
Diagnostic(ErrorCode.ERR_OvlBinaryOperatorExpected, "true"),
// (8,30): error CS1019: Overloadable unary operator expected
// public static B operator *(B x) { return null; }
Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "*"),
// (3,33): error CS0216: The operator 'A.operator true(A, A)' requires a matching operator 'false' to also be defined
// public static bool operator true(A x, A y) { return false; }
Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("A.operator true(A, A)", "false")
);
}
[WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")]
[Fact]
public void UserDefinedOperatorLocation()
{
var source = @"
public class C
{
public static C operator +(C c) { return null; }
}
";
var keywordPos = source.IndexOf('+');
var parenPos = source.IndexOf('(');
var comp = CreateCompilation(source);
var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single();
var span = symbol.Locations.Single().SourceSpan;
Assert.Equal(keywordPos, span.Start);
Assert.Equal(parenPos, span.End);
}
[WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")]
[Fact]
public void UserDefinedConversionLocation()
{
var source = @"
public class C
{
public static explicit operator string(C c) { return null; }
}
";
var keywordPos = source.IndexOf("string", StringComparison.Ordinal);
var parenPos = source.IndexOf('(');
var comp = CreateCompilation(source);
var symbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ExplicitConversionName).Single();
var span = symbol.Locations.Single().SourceSpan;
Assert.Equal(keywordPos, span.Start);
Assert.Equal(parenPos, span.End);
}
[WorkItem(787708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/787708")]
[Fact]
public void PartialAsyncMethodInTypeWithAttributes()
{
var source = @"
using System;
class Attr : Attribute
{
public int P { get; set; }
}
[Attr(P = F)]
partial class C
{
const int F = 1;
partial void M();
async partial void M() { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (15,24): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async partial void M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M"));
}
[WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")]
[Fact]
public void SubstitutedParameterEquality()
{
var source = @"
class C
{
void M<T>(T t) { }
}
";
var comp = CreateCompilation(source);
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var method = type.GetMember<MethodSymbol>("M");
var constructedMethod1 = method.Construct(type);
var constructedMethod2 = method.Construct(type);
Assert.Equal(constructedMethod1, constructedMethod2);
Assert.NotSame(constructedMethod1, constructedMethod2);
var substitutedParameter1 = constructedMethod1.Parameters.Single();
var substitutedParameter2 = constructedMethod2.Parameters.Single();
Assert.Equal(substitutedParameter1, substitutedParameter2);
Assert.NotSame(substitutedParameter1, substitutedParameter2);
}
[WorkItem(910100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910100")]
[Fact]
public void ReducedExtensionMethodParameterEquality()
{
var source = @"
static class C
{
static void M(this int i, string s) { }
}
";
var comp = CreateCompilation(source);
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var method = type.GetMember<MethodSymbol>("M");
var reducedMethod1 = method.ReduceExtensionMethod();
var reducedMethod2 = method.ReduceExtensionMethod();
Assert.Equal(reducedMethod1, reducedMethod2);
Assert.NotSame(reducedMethod1, reducedMethod2);
var extensionParameter1 = reducedMethod1.Parameters.Single();
var extensionParameter2 = reducedMethod2.Parameters.Single();
Assert.Equal(extensionParameter1, extensionParameter2);
Assert.NotSame(extensionParameter1, extensionParameter2);
}
[Fact]
public void RefReturningVoidMethod()
{
var source = @"
static class C
{
static ref void M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,16): error CS1547: Keyword 'void' cannot be used in this context
// static ref void M() { }
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 16)
);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturningVoidMethod()
{
var source = @"
static class C
{
static ref readonly void M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,25): error CS1547: Keyword 'void' cannot be used in this context
// static ref readonly void M() { }
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(4, 25)
);
}
[Fact]
public void RefReturningVoidMethodNested()
{
var source = @"
static class C
{
static void Main()
{
ref void M() { }
}
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,13): error CS1547: Keyword 'void' cannot be used in this context
// ref void M() { }
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(6, 13),
// (6,18): warning CS8321: The local function 'M' is declared but never used
// ref void M() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M").WithArguments("M").WithLocation(6, 18)
);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturningVoidMethodNested()
{
var source = @"
static class C
{
static void Main()
{
// valid
ref readonly int M1() {throw null;}
// not valid
ref readonly void M2() {M1(); throw null;}
M2();
}
}
";
var parseOptions = TestOptions.Regular;
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,22): error CS1547: Keyword 'void' cannot be used in this context
// ref readonly void M2() {M1(); throw null;}
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(10, 22)
);
}
[Fact]
public void RefReturningAsyncMethod()
{
var source = @"
static class C
{
static async ref int M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,18): error CS1073: Unexpected token 'ref'
// static async ref int M() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18),
// (4,26): 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.
// static async ref int M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 26),
// (4,26): error CS0161: 'C.M()': not all code paths return a value
// static async ref int M() { }
Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 26)
);
}
[Fact]
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public void RefReadonlyReturningAsyncMethod()
{
var source = @"
static class C
{
static async ref readonly int M() { }
}
";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,18): error CS1073: Unexpected token 'ref'
// static async ref readonly int M() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 18),
// (4,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// static async ref readonly int M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 35),
// (4,35): error CS0161: 'C.M()': not all code paths return a value
// static async ref readonly int M() { }
Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 35)
);
}
[Fact]
public void StaticMethodDoesNotRequireInstanceReceiver()
{
var source = @"
class C
{
public static int M() => 42;
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.False(method.RequiresInstanceReceiver);
}
[Fact]
public void InstanceMethodRequiresInstanceReceiver()
{
var source = @"
class C
{
public int M() => 42;
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.True(method.RequiresInstanceReceiver);
}
[Fact]
public void OrdinaryMethodIsNotConditional()
{
var source = @"
class C
{
public void M() {}
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.False(method.IsConditional);
}
[Fact]
public void ConditionalMethodIsConditional()
{
var source = @"
using System.Diagnostics;
class C
{
[Conditional(""Debug"")]
public void M() {}
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.True(method.IsConditional);
}
[Fact]
public void ConditionalMethodOverrideIsConditional()
{
var source = @"
using System.Diagnostics;
class Base
{
[Conditional(""Debug"")]
public virtual void M() {}
}
class Derived : Base
{
public override void M() {}
}";
var compilation = CreateCompilation(source).VerifyDiagnostics();
var method = compilation.GetMember<MethodSymbol>("Derived.M");
Assert.True(method.IsConditional);
}
[Fact]
public void InvalidConditionalMethodIsConditional()
{
var source = @"
using System.Diagnostics;
class C
{
[Conditional(""Debug"")]
public int M() => 42;
}";
var compilation = CreateCompilation(source).VerifyDiagnostics(
// (5,6): error CS0578: The Conditional attribute is not valid on 'C.M()' because its return type is not void
// [Conditional("Debug")]
Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""Debug"")").WithArguments("C.M()").WithLocation(5, 6));
var method = compilation.GetMember<MethodSymbol>("C.M");
Assert.True(method.IsConditional);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnNonPartial()
{
var source = @"
class C
{
void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.False(m.IsPartialDefinition);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnPartialDefinitionOnly()
{
var source = @"
partial class C
{
partial void M();
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.Null(m.PartialImplementationPart);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionWithPartialImplementation()
{
var source = @"
partial class C
{
partial void M();
partial void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.False(m.PartialImplementationPart.IsPartialDefinition);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnPartialImplementation_NonPartialClass()
{
var source = @"
class C
{
partial void M();
partial void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0751: A partial method must be declared within a partial type
// partial void M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(4, 18),
// (5,18): error CS0751: A partial method must be declared within a partial type
// partial void M() {}
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(5, 18)
);
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.False(m.PartialImplementationPart.IsPartialDefinition);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinitionOnPartialImplementationOnly()
{
var source = @"
partial class C
{
partial void M() {}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M()'
// partial void M() {}
Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M()").WithLocation(4, 18)
);
var m = comp.GetMember<MethodSymbol>("C.M").GetPublicSymbol();
Assert.False(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.Null(m.PartialImplementationPart);
}
[Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")]
public void IsPartialDefinition_ReturnsFalseFromMetadata()
{
var source = @"
public partial class C
{
public partial void M();
public partial void M() {}
}
";
CompileAndVerify(source,
sourceSymbolValidator: module =>
{
var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol();
Assert.True(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.False(m.PartialImplementationPart.IsPartialDefinition);
},
symbolValidator: module =>
{
var m = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").GetPublicSymbol();
Assert.False(m.IsPartialDefinition);
Assert.Null(m.PartialDefinitionPart);
Assert.Null(m.PartialImplementationPart);
});
}
[Fact]
public void IsPartialDefinition_OnPartialExtern()
{
var source = @"
public partial class C
{
private partial void M();
private extern partial void M();
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var syntax = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntax);
var methods = syntax.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToArray();
var partialDef = model.GetDeclaredSymbol(methods[0]);
Assert.True(partialDef.IsPartialDefinition);
var partialImpl = model.GetDeclaredSymbol(methods[1]);
Assert.False(partialImpl.IsPartialDefinition);
Assert.Same(partialDef.PartialImplementationPart, partialImpl);
Assert.Same(partialImpl.PartialDefinitionPart, partialDef);
Assert.Null(partialDef.PartialDefinitionPart);
Assert.Null(partialImpl.PartialImplementationPart);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages;
using Task = System.Threading.Tasks.Task;
namespace Roslyn.VisualStudio.DiagnosticsWindow
{
// The option page configuration is duplicated in PackageRegistration.pkgdef.
// These attributes specify the menu structure to be used in Tools | Options. These are not
// localized because they are for internal use only.
[ProvideOptionPage(typeof(InternalFeaturesOnOffPage), @"Roslyn\FeatureManager", @"Features", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(InternalComponentsOnOffPage), @"Roslyn\FeatureManager", @"Components", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(PerformanceFunctionIdPage), @"Roslyn\Performance", @"FunctionId", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(PerformanceLoggersPage), @"Roslyn\Performance", @"Loggers", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(InternalDiagnosticsPage), @"Roslyn\Diagnostics", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(InternalSolutionCrawlerPage), @"Roslyn\SolutionCrawler", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(ExperimentationPage), @"Roslyn\Experimentation", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[Guid(GuidList.guidVisualStudioDiagnosticsWindowPkgString)]
[Description("Roslyn Diagnostics Window")]
public sealed class VisualStudioDiagnosticsWindowPackage : AsyncPackage
{
private IThreadingContext _threadingContext;
/// <summary>
/// This function is called when the user clicks the menu item that shows the
/// tool window. See the Initialize method to see how the menu item is associated to
/// this function using the OleMenuCommandService service and the MenuCommand class.
/// </summary>
private void ShowToolWindow(object sender, EventArgs e)
{
_threadingContext.ThrowIfNotOnUIThread();
JoinableTaskFactory.RunAsync(async () =>
{
await ShowToolWindowAsync(typeof(DiagnosticsWindow), id: 0, create: true, this.DisposalToken).ConfigureAwait(true);
});
}
/////////////////////////////////////////////////////////////////////////////
// Overridden Package Implementation
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
var componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true);
var menuCommandService = (IMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true);
cancellationToken.ThrowIfCancellationRequested();
Assumes.Present(componentModel);
Assumes.Present(menuCommandService);
_threadingContext = componentModel.GetService<IThreadingContext>();
var workspace = componentModel.GetService<VisualStudioWorkspace>();
_ = new ForceLowMemoryMode(workspace.Services.GetService<IOptionService>());
// Add our command handlers for menu (commands must exist in the .vsct file)
if (menuCommandService is OleMenuCommandService mcs)
{
// Create the command for the tool window
var toolwndCommandID = new CommandID(GuidList.guidVisualStudioDiagnosticsWindowCmdSet, (int)PkgCmdIDList.CmdIDRoslynDiagnosticWindow);
var menuToolWin = new MenuCommand(ShowToolWindow, toolwndCommandID);
mcs.AddCommand(menuToolWin);
}
// set logger at start up
var optionService = componentModel.GetService<IGlobalOptionService>();
var remoteClientProvider = workspace.Services.GetService<IRemoteHostClientProvider>();
PerformanceLoggersPage.SetLoggers(optionService, _threadingContext, remoteClientProvider);
}
#endregion
public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType)
{
// Return this for everything, as all our windows are now async
return this;
}
protected override string GetToolWindowTitle(Type toolWindowType, int id)
{
if (toolWindowType == typeof(DiagnosticsWindow))
{
return Resources.ToolWindowTitle;
}
return null;
}
protected override Task<object> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken)
{
return Task.FromResult(new 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 System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages;
using Task = System.Threading.Tasks.Task;
namespace Roslyn.VisualStudio.DiagnosticsWindow
{
// The option page configuration is duplicated in PackageRegistration.pkgdef.
// These attributes specify the menu structure to be used in Tools | Options. These are not
// localized because they are for internal use only.
[ProvideOptionPage(typeof(InternalFeaturesOnOffPage), @"Roslyn\FeatureManager", @"Features", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(InternalComponentsOnOffPage), @"Roslyn\FeatureManager", @"Components", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(PerformanceFunctionIdPage), @"Roslyn\Performance", @"FunctionId", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(PerformanceLoggersPage), @"Roslyn\Performance", @"Loggers", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(InternalDiagnosticsPage), @"Roslyn\Diagnostics", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(InternalSolutionCrawlerPage), @"Roslyn\SolutionCrawler", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[ProvideOptionPage(typeof(ExperimentationPage), @"Roslyn\Experimentation", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)]
[Guid(GuidList.guidVisualStudioDiagnosticsWindowPkgString)]
[Description("Roslyn Diagnostics Window")]
public sealed class VisualStudioDiagnosticsWindowPackage : AsyncPackage
{
private IThreadingContext _threadingContext;
/// <summary>
/// This function is called when the user clicks the menu item that shows the
/// tool window. See the Initialize method to see how the menu item is associated to
/// this function using the OleMenuCommandService service and the MenuCommand class.
/// </summary>
private void ShowToolWindow(object sender, EventArgs e)
{
_threadingContext.ThrowIfNotOnUIThread();
JoinableTaskFactory.RunAsync(async () =>
{
await ShowToolWindowAsync(typeof(DiagnosticsWindow), id: 0, create: true, this.DisposalToken).ConfigureAwait(true);
});
}
/////////////////////////////////////////////////////////////////////////////
// Overridden Package Implementation
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
var componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true);
var menuCommandService = (IMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true);
cancellationToken.ThrowIfCancellationRequested();
Assumes.Present(componentModel);
Assumes.Present(menuCommandService);
_threadingContext = componentModel.GetService<IThreadingContext>();
var workspace = componentModel.GetService<VisualStudioWorkspace>();
_ = new ForceLowMemoryMode(workspace.Services.GetService<IOptionService>());
// Add our command handlers for menu (commands must exist in the .vsct file)
if (menuCommandService is OleMenuCommandService mcs)
{
// Create the command for the tool window
var toolwndCommandID = new CommandID(GuidList.guidVisualStudioDiagnosticsWindowCmdSet, (int)PkgCmdIDList.CmdIDRoslynDiagnosticWindow);
var menuToolWin = new MenuCommand(ShowToolWindow, toolwndCommandID);
mcs.AddCommand(menuToolWin);
}
// set logger at start up
var optionService = componentModel.GetService<IGlobalOptionService>();
var remoteClientProvider = workspace.Services.GetService<IRemoteHostClientProvider>();
PerformanceLoggersPage.SetLoggers(optionService, _threadingContext, remoteClientProvider);
}
#endregion
public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType)
{
// Return this for everything, as all our windows are now async
return this;
}
protected override string GetToolWindowTitle(Type toolWindowType, int id)
{
if (toolWindowType == typeof(DiagnosticsWindow))
{
return Resources.ToolWindowTitle;
}
return null;
}
protected override Task<object> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken)
{
return Task.FromResult(new object());
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/Progression/GraphNodeIdCreation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.CodeSchema;
using Microsoft.VisualStudio.GraphModel.Schemas;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Progression.CodeSchema;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
/// <summary>
/// A helper class that implements the creation of GraphNodeIds that matches the .dgml creation
/// by the metadata progression provider.
/// </summary>
internal static class GraphNodeIdCreation
{
public static GraphNodeId GetIdForDocument(Document document)
{
return
GraphNodeId.GetNested(
GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, new Uri(document.Project.FilePath, UriKind.RelativeOrAbsolute)),
GraphNodeId.GetPartial(CodeGraphNodeIdName.File, new Uri(document.FilePath, UriKind.RelativeOrAbsolute)));
}
internal static async Task<GraphNodeId> GetIdForNamespaceAsync(INamespaceSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var builder = new CodeQualifiedIdentifierBuilder();
var assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
builder.Assembly = assembly;
}
builder.Namespace = symbol.ToDisplayString();
return builder.ToQualifiedIdentifier();
}
internal static async Task<GraphNodeId> GetIdForTypeAsync(ITypeSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(symbol, true, solution, cancellationToken).ConfigureAwait(false);
var partials = nodes.ToArray();
if (partials.Length == 1)
{
return partials[0];
}
else
{
return GraphNodeId.GetNested(partials);
}
}
private static async Task<IEnumerable<GraphNodeId>> GetPartialsForNamespaceAndTypeAsync(ITypeSymbol symbol, bool includeNamespace, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
var items = new List<GraphNodeId>();
Uri assembly = null;
if (includeNamespace)
{
assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
}
var underlyingType = ChaseToUnderlyingType(symbol);
if (symbol.TypeKind == TypeKind.TypeParameter)
{
var typeParameter = (ITypeParameterSymbol)symbol;
if (typeParameter.TypeParameterKind == TypeParameterKind.Type)
{
if (includeNamespace && !typeParameter.ContainingNamespace.IsGlobalNamespace)
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, typeParameter.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol.ContainingType, CodeGraphNodeIdName.Type, solution, cancellationToken).ConfigureAwait(false));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, ((ITypeParameterSymbol)symbol).Ordinal.ToString()));
}
else
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, "System"));
}
else if (underlyingType.ContainingNamespace != null && !underlyingType.ContainingNamespace.IsGlobalNamespace)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, underlyingType.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol, CodeGraphNodeIdName.Type, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false));
}
return items;
}
private static async Task<GraphNodeId> GetPartialForTypeAsync(ITypeSymbol symbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
if (symbol is IArrayTypeSymbol arrayType)
{
return await GetPartialForArrayTypeAsync(arrayType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is INamedTypeSymbol namedType)
{
return await GetPartialForNamedTypeAsync(namedType, nodeName, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false);
}
else if (symbol is IPointerTypeSymbol pointerType)
{
return await GetPartialForPointerTypeAsync(pointerType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is ITypeParameterSymbol typeParameter)
{
return await GetPartialForTypeParameterSymbolAsync(typeParameter, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IDynamicTypeSymbol)
{
return GetPartialForDynamicType(nodeName);
}
throw ExceptionUtilities.Unreachable;
}
private static GraphNodeId GetPartialForDynamicType(GraphNodeIdName nodeName)
{
// We always consider this to be the "Object" type since Progression takes a very metadata-ish view of the type
return GraphNodeId.GetPartial(nodeName, "Object");
}
private static async Task<GraphNodeId> GetPartialForNamedTypeAsync(INamedTypeSymbol namedType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
// If this is a simple type, then we don't have much to do
if (namedType.ContainingType == null && Equals(namedType.ConstructedFrom, namedType) && namedType.Arity == 0)
{
return GraphNodeId.GetPartial(nodeName, namedType.Name);
}
else
{
// For a generic type, we need to populate "type" property with the following form:
//
// Type = (Name =...GenericParameterCount = GenericArguments =...ParentType =...)
//
// where "Name" contains a symbol name
// and "GenericParameterCount" contains the number of type parameters,
// and "GenericArguments" contains its type parameters' node information.
// and "ParentType" contains its containing type's node information.
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, namedType.Name));
if (namedType.Arity > 0)
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, namedType.Arity.ToString()));
}
// For the property "GenericArguments", we only populate them
// when type parameters are constructed using instance types (i.e., namedType.ConstructedFrom != namedType).
// However, there is a case where we need to populate "GenericArguments" even though arguments are not marked as "constructed"
// because a symbol is not marked as "constructed" when a type is constructed using its own type parameters.
// To distinguish this case, we use "isInGenericArguments" flag which we pass either to populate arguments recursively or to populate "ParentType".
var hasGenericArguments = (!Equals(namedType.ConstructedFrom, namedType) || isInGenericArguments) && namedType.TypeArguments != null && namedType.TypeArguments.Any();
if (hasGenericArguments)
{
var genericArguments = new List<GraphNodeId>();
foreach (var arg in namedType.TypeArguments)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(arg, includeNamespace: true, solution: solution, cancellationToken: cancellationToken, isInGenericArguments: true).ConfigureAwait(false);
genericArguments.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
partials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.GenericArgumentsIdentifier,
genericArguments.ToArray()));
}
if (namedType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(namedType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken, hasGenericArguments).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
}
private static async Task<GraphNodeId> GetPartialForPointerTypeAsync(IPointerTypeSymbol pointerType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var indirection = 1;
while (pointerType.PointedAtType.TypeKind == TypeKind.Pointer)
{
indirection++;
pointerType = (IPointerTypeSymbol)pointerType.PointedAtType;
}
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, pointerType.PointedAtType.Name));
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Indirection, indirection.ToString()));
if (pointerType.PointedAtType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(pointerType.PointedAtType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForArrayTypeAsync(IArrayTypeSymbol arrayType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
var underlyingType = ChaseToUnderlyingType(arrayType);
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, "Object"));
}
else if (underlyingType.TypeKind != TypeKind.TypeParameter)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, underlyingType.Name));
}
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.ArrayRank, arrayType.Rank.ToString()));
partials.Add(await GetPartialForTypeAsync(arrayType.ElementType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForTypeParameterSymbolAsync(ITypeParameterSymbol typeParameterSymbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
if (typeParameterSymbol.TypeParameterKind == TypeParameterKind.Method)
{
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false,
GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, typeParameterSymbol.Ordinal.ToString())));
}
else
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(typeParameterSymbol, false, solution, cancellationToken).ConfigureAwait(false);
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false, nodes.ToArray()));
}
}
private static ITypeSymbol ChaseToUnderlyingType(ITypeSymbol symbol)
{
while (symbol.TypeKind == TypeKind.Array)
{
symbol = ((IArrayTypeSymbol)symbol).ElementType;
}
while (symbol.TypeKind == TypeKind.Pointer)
{
symbol = ((IPointerTypeSymbol)symbol).PointedAtType;
}
return symbol;
}
public static async Task<GraphNodeId> GetIdForMemberAsync(ISymbol member, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
partials.AddRange(await GetPartialsForNamespaceAndTypeAsync(member.ContainingType, true, solution, cancellationToken).ConfigureAwait(false));
var parameters = member.GetParameters();
if (parameters.Any() || member.GetArity() > 0)
{
var memberPartials = new List<GraphNodeId>();
memberPartials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, member.MetadataName));
if (member.GetArity() > 0)
{
memberPartials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, member.GetArity().ToString()));
}
if (parameters.Any())
{
var parameterTypeIds = new List<GraphNodeId>();
foreach (var p in parameters)
{
var parameterIds = await GetPartialsForNamespaceAndTypeAsync(p.Type, true, solution, cancellationToken).ConfigureAwait(false);
var nodes = parameterIds.ToList();
if (p.IsRefOrOut())
{
nodes.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, ParamKind.Ref));
}
parameterTypeIds.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
if (member is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.Conversion)
{
// For explicit/implicit conversion operators, we need to include the return type in the method Id,
// because there can be several conversion operators with same parameters and only differ by return type.
// For example,
//
// public class Class1
// {
// public static explicit (explicit) operator int(Class1 c) { ... }
// public static explicit (explicit) operator double(Class1 c) { ... }
// }
var nodes = await GetPartialsForNamespaceAndTypeAsync(methodSymbol.ReturnType, true, solution, cancellationToken).ConfigureAwait(false);
var returnTypePartial = nodes.ToList();
returnTypePartial.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, Microsoft.VisualStudio.GraphModel.CodeSchema.ParamKind.Return));
var returnCollection = GraphNodeId.GetNested(returnTypePartial.ToArray());
parameterTypeIds.Add(returnCollection);
}
memberPartials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.OverloadingParameters,
parameterTypeIds.ToArray()));
}
partials.Add(GraphNodeId.GetPartial(
CodeGraphNodeIdName.Member,
MakeCollectionIfNecessary(memberPartials.ToArray())));
}
else
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Member, member.MetadataName));
}
return GraphNodeId.GetNested(partials.ToArray());
}
private static object MakeCollectionIfNecessary(GraphNodeId[] array)
{
// Place the array of GraphNodeId's into the collection if necessary, so to make them appear in VS Properties Panel
if (array.Length > 1)
{
return new GraphNodeIdCollection(false, array);
}
return GraphNodeId.GetNested(array);
}
private static IAssemblySymbol GetContainingAssembly(ISymbol symbol)
{
if (symbol.ContainingAssembly != null)
{
return symbol.ContainingAssembly;
}
if (!(symbol is ITypeSymbol typeSymbol))
{
return null;
}
var underlyingType = ChaseToUnderlyingType(typeSymbol);
if (Equals(typeSymbol, underlyingType))
{
// when symbol is for dynamic type
return null;
}
return GetContainingAssembly(underlyingType);
}
private static async Task<Uri> GetAssemblyFullPathAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var containingAssembly = GetContainingAssembly(symbol);
return await GetAssemblyFullPathAsync(containingAssembly, solution, cancellationToken).ConfigureAwait(false);
}
private static async Task<Uri> GetAssemblyFullPathAsync(IAssemblySymbol containingAssembly, Solution solution, CancellationToken cancellationToken)
{
if (containingAssembly == null)
{
return null;
}
var foundProject = solution.GetProject(containingAssembly, cancellationToken);
if (foundProject != null)
{
if (solution.Workspace is VisualStudioWorkspace)
{
// TODO: audit the OutputFilePath and whether this is bin or obj
if (!string.IsNullOrWhiteSpace(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.RelativeOrAbsolute);
}
return null;
}
}
else
{
// This symbol is not present in the source code, we need to resolve it from the references!
// If a MetadataReference returned by Compilation.GetMetadataReference(AssemblySymbol) has a path, we could use it.
foreach (var project in solution.Projects)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
if (compilation != null)
{
if (compilation.GetMetadataReference(containingAssembly) is PortableExecutableReference reference && !string.IsNullOrEmpty(reference.FilePath))
{
return new Uri(reference.FilePath, UriKind.RelativeOrAbsolute);
}
}
}
}
// If we are not in VS, return project.OutputFilePath as a reasonable fallback.
// For an example, it could be AdhocWorkspace for unit tests.
if (foundProject != null && !string.IsNullOrEmpty(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.Absolute);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForAssemblyAsync(IAssemblySymbol assemblySymbol, Solution solution, CancellationToken cancellationToken)
{
var assembly = await GetAssemblyFullPathAsync(assemblySymbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
var builder = new CodeQualifiedIdentifierBuilder();
builder.Assembly = assembly;
return builder.ToQualifiedIdentifier();
}
return null;
}
internal static async Task<GraphNodeId> GetIdForParameterAsync(IParameterSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support parameters inside methods or properties.
throw new ArgumentException("symbol");
}
var containingSymbol = symbol.ContainingSymbol;
if (containingSymbol is IMethodSymbol method && method.AssociatedSymbol != null && method.AssociatedSymbol.Kind == SymbolKind.Property)
{
var property = (IPropertySymbol)method.AssociatedSymbol;
if (property.Parameters.Any(p => p.Name == symbol.Name))
{
containingSymbol = property;
}
}
var memberId = await GetIdForMemberAsync(containingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
return memberId + GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, symbol.Name);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForLocalVariableAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support local variables inside methods or properties.
throw new ArgumentException("symbol");
}
var memberId = await GetIdForMemberAsync(symbol.ContainingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
var builder = new CodeQualifiedIdentifierBuilder(memberId);
builder.LocalVariable = symbol.Name;
builder.LocalVariableIndex = await GetLocalVariableIndexAsync(symbol, solution, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
return builder.ToQualifiedIdentifier();
}
return null;
}
/// <summary>
/// Get the position of where a given local variable is defined considering there could be multiple variables with the same name in method body.
/// For example, in "int M() { { int goo = 0; ...} { int goo = 1; ...} }",
/// the return value for the first "goo" would be 0 while the value for the second one would be 1.
/// It will be used to create a node with LocalVariableIndex for a non-zero value.
/// In the above example, hence, a node id for the first "goo" would look like (... Member=M LocalVariable=bar)
/// but an id for the second "goo" would be (... Member=M LocalVariable=bar LocalVariableIndex=1)
/// </summary>
private static async Task<int> GetLocalVariableIndexAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var pos = 0;
foreach (var reference in symbol.ContainingSymbol.DeclaringSyntaxReferences)
{
var currentNode = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
// For VB, we have to ask its parent to get local variables within this method body
// since DeclaringSyntaxReferences return statement rather than enclosing block.
if (currentNode != null && symbol.Language == LanguageNames.VisualBasic)
{
currentNode = currentNode.Parent;
}
if (currentNode != null)
{
var document = solution.GetDocument(currentNode.SyntaxTree);
if (document == null)
{
continue;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var node in currentNode.DescendantNodes())
{
var current = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (current != null && current.Name == symbol.Name && (current.Kind == SymbolKind.Local || current.Kind == SymbolKind.RangeVariable))
{
if (!current.Equals(symbol))
{
pos++;
}
else
{
return pos;
}
}
}
}
}
throw ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.CodeSchema;
using Microsoft.VisualStudio.GraphModel.Schemas;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Progression.CodeSchema;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
/// <summary>
/// A helper class that implements the creation of GraphNodeIds that matches the .dgml creation
/// by the metadata progression provider.
/// </summary>
internal static class GraphNodeIdCreation
{
public static GraphNodeId GetIdForDocument(Document document)
{
return
GraphNodeId.GetNested(
GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, new Uri(document.Project.FilePath, UriKind.RelativeOrAbsolute)),
GraphNodeId.GetPartial(CodeGraphNodeIdName.File, new Uri(document.FilePath, UriKind.RelativeOrAbsolute)));
}
internal static async Task<GraphNodeId> GetIdForNamespaceAsync(INamespaceSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var builder = new CodeQualifiedIdentifierBuilder();
var assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
builder.Assembly = assembly;
}
builder.Namespace = symbol.ToDisplayString();
return builder.ToQualifiedIdentifier();
}
internal static async Task<GraphNodeId> GetIdForTypeAsync(ITypeSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(symbol, true, solution, cancellationToken).ConfigureAwait(false);
var partials = nodes.ToArray();
if (partials.Length == 1)
{
return partials[0];
}
else
{
return GraphNodeId.GetNested(partials);
}
}
private static async Task<IEnumerable<GraphNodeId>> GetPartialsForNamespaceAndTypeAsync(ITypeSymbol symbol, bool includeNamespace, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
var items = new List<GraphNodeId>();
Uri assembly = null;
if (includeNamespace)
{
assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
}
var underlyingType = ChaseToUnderlyingType(symbol);
if (symbol.TypeKind == TypeKind.TypeParameter)
{
var typeParameter = (ITypeParameterSymbol)symbol;
if (typeParameter.TypeParameterKind == TypeParameterKind.Type)
{
if (includeNamespace && !typeParameter.ContainingNamespace.IsGlobalNamespace)
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, typeParameter.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol.ContainingType, CodeGraphNodeIdName.Type, solution, cancellationToken).ConfigureAwait(false));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, ((ITypeParameterSymbol)symbol).Ordinal.ToString()));
}
else
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, "System"));
}
else if (underlyingType.ContainingNamespace != null && !underlyingType.ContainingNamespace.IsGlobalNamespace)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, underlyingType.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol, CodeGraphNodeIdName.Type, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false));
}
return items;
}
private static async Task<GraphNodeId> GetPartialForTypeAsync(ITypeSymbol symbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
if (symbol is IArrayTypeSymbol arrayType)
{
return await GetPartialForArrayTypeAsync(arrayType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is INamedTypeSymbol namedType)
{
return await GetPartialForNamedTypeAsync(namedType, nodeName, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false);
}
else if (symbol is IPointerTypeSymbol pointerType)
{
return await GetPartialForPointerTypeAsync(pointerType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is ITypeParameterSymbol typeParameter)
{
return await GetPartialForTypeParameterSymbolAsync(typeParameter, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IDynamicTypeSymbol)
{
return GetPartialForDynamicType(nodeName);
}
throw ExceptionUtilities.Unreachable;
}
private static GraphNodeId GetPartialForDynamicType(GraphNodeIdName nodeName)
{
// We always consider this to be the "Object" type since Progression takes a very metadata-ish view of the type
return GraphNodeId.GetPartial(nodeName, "Object");
}
private static async Task<GraphNodeId> GetPartialForNamedTypeAsync(INamedTypeSymbol namedType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
// If this is a simple type, then we don't have much to do
if (namedType.ContainingType == null && Equals(namedType.ConstructedFrom, namedType) && namedType.Arity == 0)
{
return GraphNodeId.GetPartial(nodeName, namedType.Name);
}
else
{
// For a generic type, we need to populate "type" property with the following form:
//
// Type = (Name =...GenericParameterCount = GenericArguments =...ParentType =...)
//
// where "Name" contains a symbol name
// and "GenericParameterCount" contains the number of type parameters,
// and "GenericArguments" contains its type parameters' node information.
// and "ParentType" contains its containing type's node information.
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, namedType.Name));
if (namedType.Arity > 0)
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, namedType.Arity.ToString()));
}
// For the property "GenericArguments", we only populate them
// when type parameters are constructed using instance types (i.e., namedType.ConstructedFrom != namedType).
// However, there is a case where we need to populate "GenericArguments" even though arguments are not marked as "constructed"
// because a symbol is not marked as "constructed" when a type is constructed using its own type parameters.
// To distinguish this case, we use "isInGenericArguments" flag which we pass either to populate arguments recursively or to populate "ParentType".
var hasGenericArguments = (!Equals(namedType.ConstructedFrom, namedType) || isInGenericArguments) && namedType.TypeArguments != null && namedType.TypeArguments.Any();
if (hasGenericArguments)
{
var genericArguments = new List<GraphNodeId>();
foreach (var arg in namedType.TypeArguments)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(arg, includeNamespace: true, solution: solution, cancellationToken: cancellationToken, isInGenericArguments: true).ConfigureAwait(false);
genericArguments.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
partials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.GenericArgumentsIdentifier,
genericArguments.ToArray()));
}
if (namedType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(namedType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken, hasGenericArguments).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
}
private static async Task<GraphNodeId> GetPartialForPointerTypeAsync(IPointerTypeSymbol pointerType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var indirection = 1;
while (pointerType.PointedAtType.TypeKind == TypeKind.Pointer)
{
indirection++;
pointerType = (IPointerTypeSymbol)pointerType.PointedAtType;
}
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, pointerType.PointedAtType.Name));
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Indirection, indirection.ToString()));
if (pointerType.PointedAtType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(pointerType.PointedAtType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForArrayTypeAsync(IArrayTypeSymbol arrayType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
var underlyingType = ChaseToUnderlyingType(arrayType);
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, "Object"));
}
else if (underlyingType.TypeKind != TypeKind.TypeParameter)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, underlyingType.Name));
}
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.ArrayRank, arrayType.Rank.ToString()));
partials.Add(await GetPartialForTypeAsync(arrayType.ElementType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForTypeParameterSymbolAsync(ITypeParameterSymbol typeParameterSymbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
if (typeParameterSymbol.TypeParameterKind == TypeParameterKind.Method)
{
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false,
GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, typeParameterSymbol.Ordinal.ToString())));
}
else
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(typeParameterSymbol, false, solution, cancellationToken).ConfigureAwait(false);
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false, nodes.ToArray()));
}
}
private static ITypeSymbol ChaseToUnderlyingType(ITypeSymbol symbol)
{
while (symbol.TypeKind == TypeKind.Array)
{
symbol = ((IArrayTypeSymbol)symbol).ElementType;
}
while (symbol.TypeKind == TypeKind.Pointer)
{
symbol = ((IPointerTypeSymbol)symbol).PointedAtType;
}
return symbol;
}
public static async Task<GraphNodeId> GetIdForMemberAsync(ISymbol member, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
partials.AddRange(await GetPartialsForNamespaceAndTypeAsync(member.ContainingType, true, solution, cancellationToken).ConfigureAwait(false));
var parameters = member.GetParameters();
if (parameters.Any() || member.GetArity() > 0)
{
var memberPartials = new List<GraphNodeId>();
memberPartials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, member.MetadataName));
if (member.GetArity() > 0)
{
memberPartials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, member.GetArity().ToString()));
}
if (parameters.Any())
{
var parameterTypeIds = new List<GraphNodeId>();
foreach (var p in parameters)
{
var parameterIds = await GetPartialsForNamespaceAndTypeAsync(p.Type, true, solution, cancellationToken).ConfigureAwait(false);
var nodes = parameterIds.ToList();
if (p.IsRefOrOut())
{
nodes.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, ParamKind.Ref));
}
parameterTypeIds.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
if (member is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.Conversion)
{
// For explicit/implicit conversion operators, we need to include the return type in the method Id,
// because there can be several conversion operators with same parameters and only differ by return type.
// For example,
//
// public class Class1
// {
// public static explicit (explicit) operator int(Class1 c) { ... }
// public static explicit (explicit) operator double(Class1 c) { ... }
// }
var nodes = await GetPartialsForNamespaceAndTypeAsync(methodSymbol.ReturnType, true, solution, cancellationToken).ConfigureAwait(false);
var returnTypePartial = nodes.ToList();
returnTypePartial.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, Microsoft.VisualStudio.GraphModel.CodeSchema.ParamKind.Return));
var returnCollection = GraphNodeId.GetNested(returnTypePartial.ToArray());
parameterTypeIds.Add(returnCollection);
}
memberPartials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.OverloadingParameters,
parameterTypeIds.ToArray()));
}
partials.Add(GraphNodeId.GetPartial(
CodeGraphNodeIdName.Member,
MakeCollectionIfNecessary(memberPartials.ToArray())));
}
else
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Member, member.MetadataName));
}
return GraphNodeId.GetNested(partials.ToArray());
}
private static object MakeCollectionIfNecessary(GraphNodeId[] array)
{
// Place the array of GraphNodeId's into the collection if necessary, so to make them appear in VS Properties Panel
if (array.Length > 1)
{
return new GraphNodeIdCollection(false, array);
}
return GraphNodeId.GetNested(array);
}
private static IAssemblySymbol GetContainingAssembly(ISymbol symbol)
{
if (symbol.ContainingAssembly != null)
{
return symbol.ContainingAssembly;
}
if (!(symbol is ITypeSymbol typeSymbol))
{
return null;
}
var underlyingType = ChaseToUnderlyingType(typeSymbol);
if (Equals(typeSymbol, underlyingType))
{
// when symbol is for dynamic type
return null;
}
return GetContainingAssembly(underlyingType);
}
private static async Task<Uri> GetAssemblyFullPathAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var containingAssembly = GetContainingAssembly(symbol);
return await GetAssemblyFullPathAsync(containingAssembly, solution, cancellationToken).ConfigureAwait(false);
}
private static async Task<Uri> GetAssemblyFullPathAsync(IAssemblySymbol containingAssembly, Solution solution, CancellationToken cancellationToken)
{
if (containingAssembly == null)
{
return null;
}
var foundProject = solution.GetProject(containingAssembly, cancellationToken);
if (foundProject != null)
{
if (solution.Workspace is VisualStudioWorkspace)
{
// TODO: audit the OutputFilePath and whether this is bin or obj
if (!string.IsNullOrWhiteSpace(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.RelativeOrAbsolute);
}
return null;
}
}
else
{
// This symbol is not present in the source code, we need to resolve it from the references!
// If a MetadataReference returned by Compilation.GetMetadataReference(AssemblySymbol) has a path, we could use it.
foreach (var project in solution.Projects)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
if (compilation != null)
{
if (compilation.GetMetadataReference(containingAssembly) is PortableExecutableReference reference && !string.IsNullOrEmpty(reference.FilePath))
{
return new Uri(reference.FilePath, UriKind.RelativeOrAbsolute);
}
}
}
}
// If we are not in VS, return project.OutputFilePath as a reasonable fallback.
// For an example, it could be AdhocWorkspace for unit tests.
if (foundProject != null && !string.IsNullOrEmpty(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.Absolute);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForAssemblyAsync(IAssemblySymbol assemblySymbol, Solution solution, CancellationToken cancellationToken)
{
var assembly = await GetAssemblyFullPathAsync(assemblySymbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
var builder = new CodeQualifiedIdentifierBuilder();
builder.Assembly = assembly;
return builder.ToQualifiedIdentifier();
}
return null;
}
internal static async Task<GraphNodeId> GetIdForParameterAsync(IParameterSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support parameters inside methods or properties.
throw new ArgumentException("symbol");
}
var containingSymbol = symbol.ContainingSymbol;
if (containingSymbol is IMethodSymbol method && method.AssociatedSymbol != null && method.AssociatedSymbol.Kind == SymbolKind.Property)
{
var property = (IPropertySymbol)method.AssociatedSymbol;
if (property.Parameters.Any(p => p.Name == symbol.Name))
{
containingSymbol = property;
}
}
var memberId = await GetIdForMemberAsync(containingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
return memberId + GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, symbol.Name);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForLocalVariableAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support local variables inside methods or properties.
throw new ArgumentException("symbol");
}
var memberId = await GetIdForMemberAsync(symbol.ContainingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
var builder = new CodeQualifiedIdentifierBuilder(memberId);
builder.LocalVariable = symbol.Name;
builder.LocalVariableIndex = await GetLocalVariableIndexAsync(symbol, solution, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
return builder.ToQualifiedIdentifier();
}
return null;
}
/// <summary>
/// Get the position of where a given local variable is defined considering there could be multiple variables with the same name in method body.
/// For example, in "int M() { { int goo = 0; ...} { int goo = 1; ...} }",
/// the return value for the first "goo" would be 0 while the value for the second one would be 1.
/// It will be used to create a node with LocalVariableIndex for a non-zero value.
/// In the above example, hence, a node id for the first "goo" would look like (... Member=M LocalVariable=bar)
/// but an id for the second "goo" would be (... Member=M LocalVariable=bar LocalVariableIndex=1)
/// </summary>
private static async Task<int> GetLocalVariableIndexAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var pos = 0;
foreach (var reference in symbol.ContainingSymbol.DeclaringSyntaxReferences)
{
var currentNode = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
// For VB, we have to ask its parent to get local variables within this method body
// since DeclaringSyntaxReferences return statement rather than enclosing block.
if (currentNode != null && symbol.Language == LanguageNames.VisualBasic)
{
currentNode = currentNode.Parent;
}
if (currentNode != null)
{
var document = solution.GetDocument(currentNode.SyntaxTree);
if (document == null)
{
continue;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var node in currentNode.DescendantNodes())
{
var current = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (current != null && current.Name == symbol.Name && (current.Kind == SymbolKind.Local || current.Kind == SymbolKind.RangeVariable))
{
if (!current.Equals(symbol))
{
pos++;
}
else
{
return pos;
}
}
}
}
}
throw ExceptionUtilities.Unreachable;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Test/Semantic/Semantics/NullableConversionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class NullableConversionTests : CompilingTestBase
{
[Fact, WorkItem(544450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544450")]
public void TestBug12780()
{
string source = @"
enum E : byte { A, B }
class Program
{
static void Main()
{
E? x = 0;
System.Console.Write(x);
x = (E?) E.B;
System.Console.Write(x);
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput: "AB");
}
[Fact]
public void TestNullableConversions()
{
// IntPtr and UIntPtr violate the rules of user-defined conversions for
// backwards-compatibility reasons. All of these should compile without error.
string source = @"
using System;
class P
{
public static void Main()
{
int? x = 123;
long? y = x;
V(x.HasValue);
V(x.Value == 123);
V((int)x == 123);
V(y.HasValue);
V(y.Value == 123);
V((long)y == 123);
V((int)y == 123);
x = null;
y = x;
V(x.HasValue);
V(y.HasValue);
bool caught = false;
try
{
y = (int) y;
}
catch
{
caught = true;
}
V(caught);
}
static void V(bool b)
{
Console.Write(b ? 't' : 'f');
}
}
";
string expectedOutput = @"tttttttfft";
var verifier = CompileAndVerify(source: source, expectedOutput: expectedOutput);
}
[Fact]
public void TestLiftedUserDefinedConversions()
{
string source = @"
struct Conv
{
public static implicit operator int(Conv c)
{
return 1;
}
// DELIBERATE SPEC VIOLATION: We allow 'lifting' even though the
// return type is not a non-nullable value type.
// UNDONE: Test pointer types
public static implicit operator string(Conv c)
{
return '2'.ToString();
}
public static implicit operator double?(Conv c)
{
return 123.0;
}
static void Main()
{
Conv? c = new Conv();
int? i = c;
string s = c;
double? d = c;
V(i.HasValue);
V(i == 1);
V(s != null);
V(s.Length == 1);
V(s[0] == '2');
V(d.HasValue);
V(d == 123.0);
c = null;
i = c;
s = c;
d = c;
V(!i.HasValue);
V(s == null);
V(!d.HasValue);
}
static void V(bool f)
{
System.Console.Write(f ? 't' : 'f');
}
}
";
string expectedOutput = @"tttttttttt";
var verifier = CompileAndVerify(source: source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(529279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529279")]
public void TestNullableWithGenericConstraints01()
{
string source = @"
class GenC<T, U> where T : struct, U where U : class
{
public void Test(T t)
{
T? nt = t;
U valueUn = nt;
System.Console.WriteLine(valueUn.ToString());
}
}
interface I1 { }
struct S1 : I1 { public override string ToString() { return ""Hola""; } }
static class Program
{
static void Main()
{
(new GenC<S1, I1>()).Test(default(S1));
}
}";
CompileAndVerify(source, expectedOutput: "Hola");
}
[Fact, WorkItem(543996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543996")]
public void TestNonLiftedUDCOnStruct()
{
string source = @"using System;
struct A
{
public C CFld;
}
class C
{
public A AFld;
public static implicit operator A(C c)
{
return c.AFld;
}
public static explicit operator C(A a)
{
return a.CFld;
}
}
public class Test
{
public static void Main()
{
A a = new A();
a.CFld = new C();
a.CFld.AFld = a;
C c = a.CFld;
A? nubA = c; // Assert here
Console.Write(nubA.HasValue && nubA.Value.CFld == c);
C nubC = (C)nubA;
Console.Write(nubC.AFld.CFld == c);
}
}
";
CompileAndVerify(source, expectedOutput: "TrueTrue");
}
[Fact, WorkItem(543997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543997")]
public void TestImplicitLiftedUDCOnStruct()
{
string source = @"using System;
namespace Test
{
static class Program
{
static void Main()
{
S.v = 0;
S? S2 = 123; // not lifted, int=>int?, int?=>S, S=>S?
Console.WriteLine(S.v == 123);
}
}
public struct S
{
public static int v;
// s == null, return v = -1
public static implicit operator S(int? s)
{
Console.Write(""Imp S::int? -> S "");
S ss = new S();
S.v = s ?? -1;
return ss;
}
}
}
";
CompileAndVerify(source, expectedOutput: "Imp S::int? -> S True");
}
[Fact]
public void TestExplicitUnliftedUDC()
{
string source = @"
using System;
namespace Test
{
static class Program
{
static void Main()
{
int? i = 123;
C c = (C)i;
Console.WriteLine(c.v == 123 ? 't' : 'f');
}
}
public class C
{
public readonly int v;
public C(int v) { this.v = v; }
public static implicit operator C(int v)
{
Console.Write(v);
return new C(v);
}
}
}
";
CompileAndVerify(source, expectedOutput: "123t");
}
[Fact, WorkItem(545091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545091")]
public void TestImplicitUDCInNullCoalescingOperand()
{
string source = @"using System;
class C
{
public static implicit operator C(string s)
{
Console.Write(""implicit "");
return new C();
}
public override string ToString() { return ""C""; }
}
class A
{
static void Main()
{
var ret = ""str"" ?? new C();
Console.Write(ret.GetType());
}
}
";
CompileAndVerify(source, expectedOutput: "implicit C");
}
[WorkItem(545377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545377")]
[Fact]
public void TestLiftedVsUnlifted()
{
// The correct behavior here is to choose operator 2. Binary operator overload
// resolution should determine that the best built-in addition operator is
// lifted int + int, which has signature int? + int? --> int?. However, the
// native compiler gets this wrong. The native compiler, pretends
// that there are *three* lifted operators: int + int? --> int?, int? + int --> int?,
// and int? + int? --> int?. Therefore the native compiler decides that the
// int? + int --> int operator is the best, because it is the applicable operator
// with the most specific types, and therefore chooses operator 1.
//
// This does not match the specification.
// It seems reasonable that if someone has done this very strange thing of making
// conversions S --> int and S --> int?, that they probably intend for the
// lifted operation to use the conversion specifically designed for nullables.
//
// Roslyn matches the specification and takes the break from the native compiler.
// See the next test case for more thoughts on this.
string source = @"
using System;
public struct S
{
public static implicit operator int(S n) // 1 native compiler
{
Console.WriteLine(1);
return 0;
}
public static implicit operator int?(S n) // 2 Roslyn compiler
{
Console.WriteLine(2);
return null;
}
public static void Main()
{
int? qa = 5;
S b = default(S);
var sum = qa + b;
}
}
";
CompileAndVerify(source, expectedOutput: "2");
}
[WorkItem(545377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545377")]
[Fact]
public void TestLiftedVsUnlifted_Combinations()
{
// The point of this test is to show that Roslyn and the native compiler
// agree on resolution of *conversions* but do not agree on resolution
// of *binary operators*. That is, we wish to show that we are isolating
// the breaking change to the binary operator overload resolution, and not
// to the conversion resolution code. See the previous bug for details.
string source = @"
using System;
struct S___A
{
public static implicit operator int(S___A n) { Console.Write('A'); return 0; }
}
struct S__B_
{
public static implicit operator int(S__B_? n) { Console.Write('B'); return 0; }
}
struct S__BA
{
public static implicit operator int(S__BA? n) { Console.Write('B'); return 0; }
public static implicit operator int(S__BA n) { Console.Write('A'); return 0; }
}
struct S_C__
{
public static implicit operator int?(S_C__ n) { Console.Write('C'); return 0; }
}
struct S_C_A
{
public static implicit operator int?(S_C_A n) { Console.Write('C'); return 0; }
public static implicit operator int(S_C_A n) { Console.Write('A'); return 0; }
}
struct S_CB_
{
public static implicit operator int?(S_CB_ n) { Console.Write('C'); return 0; }
public static implicit operator int(S_CB_? n) { Console.Write('B'); return 0; }
}
struct S_CBA
{
public static implicit operator int?(S_CBA n) { Console.Write('C'); return 0; }
public static implicit operator int(S_CBA? n) { Console.Write('B'); return 0; }
public static implicit operator int(S_CBA n) { Console.Write('A'); return 0; }
}
struct SD___
{
public static implicit operator int?(SD___? n){ Console.Write('D'); return 0; }
}
struct SD__A
{
public static implicit operator int?(SD__A? n){ Console.Write('D'); return 0; }
public static implicit operator int(SD__A n) { Console.Write('A'); return 0; }
}
struct SD_B_
{
public static implicit operator int?(SD_B_? n){ Console.Write('D'); return 0; }
public static implicit operator int(SD_B_? n) { Console.Write('B'); return 0; }
}
struct SD_BA
{
public static implicit operator int?(SD_BA? n){ Console.Write('D'); return 0; }
public static implicit operator int(SD_BA? n) { Console.Write('B'); return 0; }
public static implicit operator int(SD_BA n) { Console.Write('A'); return 0; }
}
struct SDC__
{
public static implicit operator int?(SDC__? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDC__ n) { Console.Write('C'); return 0; }
}
struct SDC_A
{
public static implicit operator int?(SDC_A? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDC_A n) { Console.Write('C'); return 0; }
public static implicit operator int(SDC_A n) { Console.Write('A'); return 0; }
}
struct SDCB_
{
public static implicit operator int?(SDCB_? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDCB_ n) { Console.Write('C'); return 0; }
public static implicit operator int(SDCB_? n) { Console.Write('B'); return 0; }
}
struct SDCBA
{
public static implicit operator int?(SDCBA? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDCBA n) { Console.Write('C'); return 0; }
public static implicit operator int(SDCBA? n) { Console.Write('B'); return 0; }
public static implicit operator int(SDCBA n) { Console.Write('A'); return 0; }
}
class Program
{
static S___A s___a1;
static S__B_ s__b_1;
static S__BA s__ba1;
static S_C__ s_c__1;
static S_C_A s_c_a1;
static S_CB_ s_cb_1;
static S_CBA s_cba1;
static SD___ sd___1;
static SD__A sd__a1;
static SD_B_ sd_b_1;
static SD_BA sd_ba1;
static SDC__ sdc__1;
static SDC_A sdc_a1;
static SDCB_ sdcb_1;
static SDCBA sdcba1;
static S___A? s___a2;
static S__B_? s__b_2;
static S__BA? s__ba2;
static S_C__? s_c__2;
static S_C_A? s_c_a2;
static S_CB_? s_cb_2;
static S_CBA? s_cba2;
static SD___? sd___2;
static SD__A? sd__a2;
static SD_B_? sd_b_2;
static SD_BA? sd_ba2;
static SDC__? sdc__2;
static SDC_A? sdc_a2;
static SDCB_? sdcb_2;
static SDCBA? sdcba2;
static int i1 = 0;
static int? i2 = 0;
static void Main()
{
TestConversions();
Console.WriteLine();
TestAdditions();
}
static void TestConversions()
{
i1 = s___a1;
i1 = s__b_1;
i1 = s__ba1;
// i1 = s_c__1;
i1 = s_c_a1;
i1 = s_cb_1;
i1 = s_cba1;
// i1 = sd___1;
i1 = sd__a1;
i1 = sd_b_1;
i1 = sd_ba1;
// i1 = sdc__1;
i1 = sdc_a1;
i1 = sdcb_1;
i1 = sdcba1;
// i1 = s___a2;
i1 = s__b_2;
i1 = s__ba2;
// i1 = s_c__2;
// i1 = s_c_a2;
i1 = s_cb_2;
i1 = s_cba2;
//i1 = sd___2;
//i1 = sd__a2;
i1 = sd_b_2;
i1 = sd_ba2;
//i1 = sdc__2;
//i1 = sdc_a2;
i1 = sdcb_2;
i1 = sdcba2;
i2 = s___a1;
i2 = s__b_1;
i2 = s__ba1;
i2 = s_c__1;
i2 = s_c_a1;
i2 = s_cb_1;
i2 = s_cba1;
i2 = sd___1;
i2 = sd__a1;
i2 = sd_b_1;
i2 = sd_ba1;
i2 = sdc__1;
i2 = sdc_a1;
i2 = sdcb_1;
i2 = sdcba1;
i2 = s___a2;
i2 = s__b_2;
i2 = s__ba2;
i2 = s_c__2;
i2 = s_c_a2;
//i2 = s_cb_2;
//i2 = s_cba2;
i2 = sd___2;
i2 = sd__a2;
i2 = sd_b_2;
i2 = sd_ba2;
i2 = sdc__2;
i2 = sdc_a2;
i2 = sdcb_2;
i2 = sdcba2;
}
static void TestAdditions()
{
i2 = i1 + s___a1;
i2 = i1 + s__b_1;
i2 = i1 + s__ba1;
i2 = i1 + s_c__1;
i2 = i1 + s_c_a1;
i2 = i1 + s_cb_1;
i2 = i1 + s_cba1;
i2 = i1 + sd___1;
i2 = i1 + sd__a1;
i2 = i1 + sd_b_1;
i2 = i1 + sd_ba1;
i2 = i1 + sdc__1;
i2 = i1 + sdc_a1;
i2 = i1 + sdcb_1;
i2 = i1 + sdcba1;
i2 = i1 + s___a2;
i2 = i1 + s__b_2;
i2 = i1 + s__ba2;
i2 = i1 + s_c__2;
i2 = i1 + s_c_a2;
i2 = i1 + s_cb_2;
i2 = i1 + s_cba2;
i2 = i1 + sd___2;
i2 = i1 + sd__a2;
i2 = i1 + sd_b_2;
i2 = i1 + sd_ba2;
i2 = i1 + sdc__2;
i2 = i1 + sdc_a2;
i2 = i1 + sdcb_2;
i2 = i1 + sdcba2;
i2 = i2 + s___a1;
i2 = i2 + s__b_1;
i2 = i2 + s__ba1;
i2 = i2 + s_c__1;
i2 = i2 + s_c_a1;
i2 = i2 + s_cb_1;
i2 = i2 + s_cba1;
i2 = i2 + sd___1;
i2 = i2 + sd__a1;
i2 = i2 + sd_b_1;
i2 = i2 + sd_ba1;
i2 = i2 + sdc__1;
i2 = i2 + sdc_a1;
i2 = i2 + sdcb_1;
i2 = i2 + sdcba1;
i2 = i2 + s___a2;
i2 = i2 + s__b_2;
i2 = i2 + s__ba2;
i2 = i2 + s_c__2;
i2 = i2 + s_c_a2;
// i2 = i2 + s_cb_2; // Native compiler allows these because it actually converts to int,
// i2 = i2 + s_cba2; // not int?, which is not ambiguous. Roslyn takes the breaking change.
i2 = i2 + sd___2;
i2 = i2 + sd__a2;
i2 = i2 + sd_b_2;
i2 = i2 + sd_ba2;
i2 = i2 + sdc__2;
i2 = i2 + sdc_a2;
i2 = i2 + sdcb_2;
i2 = i2 + sdcba2;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithWarningLevel(0));
// Roslyn and native compiler both produce ABAABAABAABABBBBBBBBABACCCCDADACCCCBBDDDDDDDD
// for straight conversions.
// Because Roslyn (correctly) prefers converting to int? instead of int when doing lifted addition,
// native compiler produces ABACABADABACABABBBBDDBBDDBBABACABADABACABABBDDBBDDBB for additions.
// Roslyn compiler produces ABACABADABACABABBBBDDBBDDBBABACCCCDADACCCCBBDDDDDDDD. That is,
// preference is given to int?-returning conversions C and D over int-returning A and B.
string expected = @"ABAABAABAABABBBBBBBBABACCCCDADACCCCBBDDDDDDDD
ABACABADABACABABBBBDDBBDDBBABACCCCDADACCCCBBDDDDDDDD";
CompileAndVerify(compilation, expectedOutput: expected);
}
[Fact]
[WorkItem(1084278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084278")]
public void NullableConversionFromFloatingPointConst()
{
var source = @"
class C
{
void Use(int? p)
{
}
void Test()
{
int? i;
// double checks
i = (int?)3.5d;
i = (int?)double.MaxValue;
i = (int?)double.NaN;
i = (int?)double.NegativeInfinity;
i = (int?)double.PositiveInfinity;
// float checks
i = (int?)3.5d;
i = (int?)float.MaxValue;
i = (int?)float.NaN;
i = (int?)float.NegativeInfinity;
i = (int?)float.PositiveInfinity;
Use(i);
unchecked {
// double checks
i = (int?)3.5d;
i = (int?)double.MaxValue;
i = (int?)double.NaN;
i = (int?)double.NegativeInfinity;
i = (int?)double.PositiveInfinity;
// float checks
i = (int?)3.5d;
i = (int?)float.MaxValue;
i = (int?)float.NaN;
i = (int?)float.NegativeInfinity;
i = (int?)float.PositiveInfinity;
}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.MaxValue;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.MaxValue").WithArguments("double", "int?").WithLocation(15, 13),
// (16,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.NaN;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.NaN").WithArguments("double", "int?").WithLocation(16, 13),
// (17,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.NegativeInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.NegativeInfinity").WithArguments("double", "int?").WithLocation(17, 13),
// (18,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.PositiveInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.PositiveInfinity").WithArguments("double", "int?").WithLocation(18, 13),
// (22,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.MaxValue;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.MaxValue").WithArguments("float", "int?").WithLocation(22, 13),
// (23,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.NaN;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.NaN").WithArguments("float", "int?").WithLocation(23, 13),
// (24,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.NegativeInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.NegativeInfinity").WithArguments("float", "int?").WithLocation(24, 13),
// (25,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.PositiveInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.PositiveInfinity").WithArguments("float", "int?").WithLocation(25, 13));
var syntaxTree = compilation.SyntaxTrees.First();
var target = syntaxTree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ToList()[2];
var operand = target.Expression;
Assert.Equal("double.NaN", operand.ToFullString());
// Note: there is a valid conversion here at the type level. It's the process of evaluating the conversion, which for
// constants happens at compile time, that triggers the error.
HashSet<DiagnosticInfo> unused = null;
var bag = DiagnosticBag.GetInstance();
var nullableIntType = compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(compilation.GetSpecialType(SpecialType.System_Int32));
var conversion = compilation.Conversions.ClassifyConversionFromExpression(
compilation.GetBinder(target).BindExpression(operand, bag),
nullableIntType,
ref unused);
Assert.True(conversion.IsExplicit && conversion.IsNullable);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class NullableConversionTests : CompilingTestBase
{
[Fact, WorkItem(544450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544450")]
public void TestBug12780()
{
string source = @"
enum E : byte { A, B }
class Program
{
static void Main()
{
E? x = 0;
System.Console.Write(x);
x = (E?) E.B;
System.Console.Write(x);
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput: "AB");
}
[Fact]
public void TestNullableConversions()
{
// IntPtr and UIntPtr violate the rules of user-defined conversions for
// backwards-compatibility reasons. All of these should compile without error.
string source = @"
using System;
class P
{
public static void Main()
{
int? x = 123;
long? y = x;
V(x.HasValue);
V(x.Value == 123);
V((int)x == 123);
V(y.HasValue);
V(y.Value == 123);
V((long)y == 123);
V((int)y == 123);
x = null;
y = x;
V(x.HasValue);
V(y.HasValue);
bool caught = false;
try
{
y = (int) y;
}
catch
{
caught = true;
}
V(caught);
}
static void V(bool b)
{
Console.Write(b ? 't' : 'f');
}
}
";
string expectedOutput = @"tttttttfft";
var verifier = CompileAndVerify(source: source, expectedOutput: expectedOutput);
}
[Fact]
public void TestLiftedUserDefinedConversions()
{
string source = @"
struct Conv
{
public static implicit operator int(Conv c)
{
return 1;
}
// DELIBERATE SPEC VIOLATION: We allow 'lifting' even though the
// return type is not a non-nullable value type.
// UNDONE: Test pointer types
public static implicit operator string(Conv c)
{
return '2'.ToString();
}
public static implicit operator double?(Conv c)
{
return 123.0;
}
static void Main()
{
Conv? c = new Conv();
int? i = c;
string s = c;
double? d = c;
V(i.HasValue);
V(i == 1);
V(s != null);
V(s.Length == 1);
V(s[0] == '2');
V(d.HasValue);
V(d == 123.0);
c = null;
i = c;
s = c;
d = c;
V(!i.HasValue);
V(s == null);
V(!d.HasValue);
}
static void V(bool f)
{
System.Console.Write(f ? 't' : 'f');
}
}
";
string expectedOutput = @"tttttttttt";
var verifier = CompileAndVerify(source: source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(529279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529279")]
public void TestNullableWithGenericConstraints01()
{
string source = @"
class GenC<T, U> where T : struct, U where U : class
{
public void Test(T t)
{
T? nt = t;
U valueUn = nt;
System.Console.WriteLine(valueUn.ToString());
}
}
interface I1 { }
struct S1 : I1 { public override string ToString() { return ""Hola""; } }
static class Program
{
static void Main()
{
(new GenC<S1, I1>()).Test(default(S1));
}
}";
CompileAndVerify(source, expectedOutput: "Hola");
}
[Fact, WorkItem(543996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543996")]
public void TestNonLiftedUDCOnStruct()
{
string source = @"using System;
struct A
{
public C CFld;
}
class C
{
public A AFld;
public static implicit operator A(C c)
{
return c.AFld;
}
public static explicit operator C(A a)
{
return a.CFld;
}
}
public class Test
{
public static void Main()
{
A a = new A();
a.CFld = new C();
a.CFld.AFld = a;
C c = a.CFld;
A? nubA = c; // Assert here
Console.Write(nubA.HasValue && nubA.Value.CFld == c);
C nubC = (C)nubA;
Console.Write(nubC.AFld.CFld == c);
}
}
";
CompileAndVerify(source, expectedOutput: "TrueTrue");
}
[Fact, WorkItem(543997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543997")]
public void TestImplicitLiftedUDCOnStruct()
{
string source = @"using System;
namespace Test
{
static class Program
{
static void Main()
{
S.v = 0;
S? S2 = 123; // not lifted, int=>int?, int?=>S, S=>S?
Console.WriteLine(S.v == 123);
}
}
public struct S
{
public static int v;
// s == null, return v = -1
public static implicit operator S(int? s)
{
Console.Write(""Imp S::int? -> S "");
S ss = new S();
S.v = s ?? -1;
return ss;
}
}
}
";
CompileAndVerify(source, expectedOutput: "Imp S::int? -> S True");
}
[Fact]
public void TestExplicitUnliftedUDC()
{
string source = @"
using System;
namespace Test
{
static class Program
{
static void Main()
{
int? i = 123;
C c = (C)i;
Console.WriteLine(c.v == 123 ? 't' : 'f');
}
}
public class C
{
public readonly int v;
public C(int v) { this.v = v; }
public static implicit operator C(int v)
{
Console.Write(v);
return new C(v);
}
}
}
";
CompileAndVerify(source, expectedOutput: "123t");
}
[Fact, WorkItem(545091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545091")]
public void TestImplicitUDCInNullCoalescingOperand()
{
string source = @"using System;
class C
{
public static implicit operator C(string s)
{
Console.Write(""implicit "");
return new C();
}
public override string ToString() { return ""C""; }
}
class A
{
static void Main()
{
var ret = ""str"" ?? new C();
Console.Write(ret.GetType());
}
}
";
CompileAndVerify(source, expectedOutput: "implicit C");
}
[WorkItem(545377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545377")]
[Fact]
public void TestLiftedVsUnlifted()
{
// The correct behavior here is to choose operator 2. Binary operator overload
// resolution should determine that the best built-in addition operator is
// lifted int + int, which has signature int? + int? --> int?. However, the
// native compiler gets this wrong. The native compiler, pretends
// that there are *three* lifted operators: int + int? --> int?, int? + int --> int?,
// and int? + int? --> int?. Therefore the native compiler decides that the
// int? + int --> int operator is the best, because it is the applicable operator
// with the most specific types, and therefore chooses operator 1.
//
// This does not match the specification.
// It seems reasonable that if someone has done this very strange thing of making
// conversions S --> int and S --> int?, that they probably intend for the
// lifted operation to use the conversion specifically designed for nullables.
//
// Roslyn matches the specification and takes the break from the native compiler.
// See the next test case for more thoughts on this.
string source = @"
using System;
public struct S
{
public static implicit operator int(S n) // 1 native compiler
{
Console.WriteLine(1);
return 0;
}
public static implicit operator int?(S n) // 2 Roslyn compiler
{
Console.WriteLine(2);
return null;
}
public static void Main()
{
int? qa = 5;
S b = default(S);
var sum = qa + b;
}
}
";
CompileAndVerify(source, expectedOutput: "2");
}
[WorkItem(545377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545377")]
[Fact]
public void TestLiftedVsUnlifted_Combinations()
{
// The point of this test is to show that Roslyn and the native compiler
// agree on resolution of *conversions* but do not agree on resolution
// of *binary operators*. That is, we wish to show that we are isolating
// the breaking change to the binary operator overload resolution, and not
// to the conversion resolution code. See the previous bug for details.
string source = @"
using System;
struct S___A
{
public static implicit operator int(S___A n) { Console.Write('A'); return 0; }
}
struct S__B_
{
public static implicit operator int(S__B_? n) { Console.Write('B'); return 0; }
}
struct S__BA
{
public static implicit operator int(S__BA? n) { Console.Write('B'); return 0; }
public static implicit operator int(S__BA n) { Console.Write('A'); return 0; }
}
struct S_C__
{
public static implicit operator int?(S_C__ n) { Console.Write('C'); return 0; }
}
struct S_C_A
{
public static implicit operator int?(S_C_A n) { Console.Write('C'); return 0; }
public static implicit operator int(S_C_A n) { Console.Write('A'); return 0; }
}
struct S_CB_
{
public static implicit operator int?(S_CB_ n) { Console.Write('C'); return 0; }
public static implicit operator int(S_CB_? n) { Console.Write('B'); return 0; }
}
struct S_CBA
{
public static implicit operator int?(S_CBA n) { Console.Write('C'); return 0; }
public static implicit operator int(S_CBA? n) { Console.Write('B'); return 0; }
public static implicit operator int(S_CBA n) { Console.Write('A'); return 0; }
}
struct SD___
{
public static implicit operator int?(SD___? n){ Console.Write('D'); return 0; }
}
struct SD__A
{
public static implicit operator int?(SD__A? n){ Console.Write('D'); return 0; }
public static implicit operator int(SD__A n) { Console.Write('A'); return 0; }
}
struct SD_B_
{
public static implicit operator int?(SD_B_? n){ Console.Write('D'); return 0; }
public static implicit operator int(SD_B_? n) { Console.Write('B'); return 0; }
}
struct SD_BA
{
public static implicit operator int?(SD_BA? n){ Console.Write('D'); return 0; }
public static implicit operator int(SD_BA? n) { Console.Write('B'); return 0; }
public static implicit operator int(SD_BA n) { Console.Write('A'); return 0; }
}
struct SDC__
{
public static implicit operator int?(SDC__? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDC__ n) { Console.Write('C'); return 0; }
}
struct SDC_A
{
public static implicit operator int?(SDC_A? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDC_A n) { Console.Write('C'); return 0; }
public static implicit operator int(SDC_A n) { Console.Write('A'); return 0; }
}
struct SDCB_
{
public static implicit operator int?(SDCB_? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDCB_ n) { Console.Write('C'); return 0; }
public static implicit operator int(SDCB_? n) { Console.Write('B'); return 0; }
}
struct SDCBA
{
public static implicit operator int?(SDCBA? n){ Console.Write('D'); return 0; }
public static implicit operator int?(SDCBA n) { Console.Write('C'); return 0; }
public static implicit operator int(SDCBA? n) { Console.Write('B'); return 0; }
public static implicit operator int(SDCBA n) { Console.Write('A'); return 0; }
}
class Program
{
static S___A s___a1;
static S__B_ s__b_1;
static S__BA s__ba1;
static S_C__ s_c__1;
static S_C_A s_c_a1;
static S_CB_ s_cb_1;
static S_CBA s_cba1;
static SD___ sd___1;
static SD__A sd__a1;
static SD_B_ sd_b_1;
static SD_BA sd_ba1;
static SDC__ sdc__1;
static SDC_A sdc_a1;
static SDCB_ sdcb_1;
static SDCBA sdcba1;
static S___A? s___a2;
static S__B_? s__b_2;
static S__BA? s__ba2;
static S_C__? s_c__2;
static S_C_A? s_c_a2;
static S_CB_? s_cb_2;
static S_CBA? s_cba2;
static SD___? sd___2;
static SD__A? sd__a2;
static SD_B_? sd_b_2;
static SD_BA? sd_ba2;
static SDC__? sdc__2;
static SDC_A? sdc_a2;
static SDCB_? sdcb_2;
static SDCBA? sdcba2;
static int i1 = 0;
static int? i2 = 0;
static void Main()
{
TestConversions();
Console.WriteLine();
TestAdditions();
}
static void TestConversions()
{
i1 = s___a1;
i1 = s__b_1;
i1 = s__ba1;
// i1 = s_c__1;
i1 = s_c_a1;
i1 = s_cb_1;
i1 = s_cba1;
// i1 = sd___1;
i1 = sd__a1;
i1 = sd_b_1;
i1 = sd_ba1;
// i1 = sdc__1;
i1 = sdc_a1;
i1 = sdcb_1;
i1 = sdcba1;
// i1 = s___a2;
i1 = s__b_2;
i1 = s__ba2;
// i1 = s_c__2;
// i1 = s_c_a2;
i1 = s_cb_2;
i1 = s_cba2;
//i1 = sd___2;
//i1 = sd__a2;
i1 = sd_b_2;
i1 = sd_ba2;
//i1 = sdc__2;
//i1 = sdc_a2;
i1 = sdcb_2;
i1 = sdcba2;
i2 = s___a1;
i2 = s__b_1;
i2 = s__ba1;
i2 = s_c__1;
i2 = s_c_a1;
i2 = s_cb_1;
i2 = s_cba1;
i2 = sd___1;
i2 = sd__a1;
i2 = sd_b_1;
i2 = sd_ba1;
i2 = sdc__1;
i2 = sdc_a1;
i2 = sdcb_1;
i2 = sdcba1;
i2 = s___a2;
i2 = s__b_2;
i2 = s__ba2;
i2 = s_c__2;
i2 = s_c_a2;
//i2 = s_cb_2;
//i2 = s_cba2;
i2 = sd___2;
i2 = sd__a2;
i2 = sd_b_2;
i2 = sd_ba2;
i2 = sdc__2;
i2 = sdc_a2;
i2 = sdcb_2;
i2 = sdcba2;
}
static void TestAdditions()
{
i2 = i1 + s___a1;
i2 = i1 + s__b_1;
i2 = i1 + s__ba1;
i2 = i1 + s_c__1;
i2 = i1 + s_c_a1;
i2 = i1 + s_cb_1;
i2 = i1 + s_cba1;
i2 = i1 + sd___1;
i2 = i1 + sd__a1;
i2 = i1 + sd_b_1;
i2 = i1 + sd_ba1;
i2 = i1 + sdc__1;
i2 = i1 + sdc_a1;
i2 = i1 + sdcb_1;
i2 = i1 + sdcba1;
i2 = i1 + s___a2;
i2 = i1 + s__b_2;
i2 = i1 + s__ba2;
i2 = i1 + s_c__2;
i2 = i1 + s_c_a2;
i2 = i1 + s_cb_2;
i2 = i1 + s_cba2;
i2 = i1 + sd___2;
i2 = i1 + sd__a2;
i2 = i1 + sd_b_2;
i2 = i1 + sd_ba2;
i2 = i1 + sdc__2;
i2 = i1 + sdc_a2;
i2 = i1 + sdcb_2;
i2 = i1 + sdcba2;
i2 = i2 + s___a1;
i2 = i2 + s__b_1;
i2 = i2 + s__ba1;
i2 = i2 + s_c__1;
i2 = i2 + s_c_a1;
i2 = i2 + s_cb_1;
i2 = i2 + s_cba1;
i2 = i2 + sd___1;
i2 = i2 + sd__a1;
i2 = i2 + sd_b_1;
i2 = i2 + sd_ba1;
i2 = i2 + sdc__1;
i2 = i2 + sdc_a1;
i2 = i2 + sdcb_1;
i2 = i2 + sdcba1;
i2 = i2 + s___a2;
i2 = i2 + s__b_2;
i2 = i2 + s__ba2;
i2 = i2 + s_c__2;
i2 = i2 + s_c_a2;
// i2 = i2 + s_cb_2; // Native compiler allows these because it actually converts to int,
// i2 = i2 + s_cba2; // not int?, which is not ambiguous. Roslyn takes the breaking change.
i2 = i2 + sd___2;
i2 = i2 + sd__a2;
i2 = i2 + sd_b_2;
i2 = i2 + sd_ba2;
i2 = i2 + sdc__2;
i2 = i2 + sdc_a2;
i2 = i2 + sdcb_2;
i2 = i2 + sdcba2;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithWarningLevel(0));
// Roslyn and native compiler both produce ABAABAABAABABBBBBBBBABACCCCDADACCCCBBDDDDDDDD
// for straight conversions.
// Because Roslyn (correctly) prefers converting to int? instead of int when doing lifted addition,
// native compiler produces ABACABADABACABABBBBDDBBDDBBABACABADABACABABBDDBBDDBB for additions.
// Roslyn compiler produces ABACABADABACABABBBBDDBBDDBBABACCCCDADACCCCBBDDDDDDDD. That is,
// preference is given to int?-returning conversions C and D over int-returning A and B.
string expected = @"ABAABAABAABABBBBBBBBABACCCCDADACCCCBBDDDDDDDD
ABACABADABACABABBBBDDBBDDBBABACCCCDADACCCCBBDDDDDDDD";
CompileAndVerify(compilation, expectedOutput: expected);
}
[Fact]
[WorkItem(1084278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084278")]
public void NullableConversionFromFloatingPointConst()
{
var source = @"
class C
{
void Use(int? p)
{
}
void Test()
{
int? i;
// double checks
i = (int?)3.5d;
i = (int?)double.MaxValue;
i = (int?)double.NaN;
i = (int?)double.NegativeInfinity;
i = (int?)double.PositiveInfinity;
// float checks
i = (int?)3.5d;
i = (int?)float.MaxValue;
i = (int?)float.NaN;
i = (int?)float.NegativeInfinity;
i = (int?)float.PositiveInfinity;
Use(i);
unchecked {
// double checks
i = (int?)3.5d;
i = (int?)double.MaxValue;
i = (int?)double.NaN;
i = (int?)double.NegativeInfinity;
i = (int?)double.PositiveInfinity;
// float checks
i = (int?)3.5d;
i = (int?)float.MaxValue;
i = (int?)float.NaN;
i = (int?)float.NegativeInfinity;
i = (int?)float.PositiveInfinity;
}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.MaxValue;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.MaxValue").WithArguments("double", "int?").WithLocation(15, 13),
// (16,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.NaN;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.NaN").WithArguments("double", "int?").WithLocation(16, 13),
// (17,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.NegativeInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.NegativeInfinity").WithArguments("double", "int?").WithLocation(17, 13),
// (18,13): error CS0030: Cannot convert type 'double' to 'int?'
// i = (int?)double.PositiveInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)double.PositiveInfinity").WithArguments("double", "int?").WithLocation(18, 13),
// (22,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.MaxValue;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.MaxValue").WithArguments("float", "int?").WithLocation(22, 13),
// (23,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.NaN;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.NaN").WithArguments("float", "int?").WithLocation(23, 13),
// (24,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.NegativeInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.NegativeInfinity").WithArguments("float", "int?").WithLocation(24, 13),
// (25,13): error CS0030: Cannot convert type 'float' to 'int?'
// i = (int?)float.PositiveInfinity;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)float.PositiveInfinity").WithArguments("float", "int?").WithLocation(25, 13));
var syntaxTree = compilation.SyntaxTrees.First();
var target = syntaxTree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ToList()[2];
var operand = target.Expression;
Assert.Equal("double.NaN", operand.ToFullString());
// Note: there is a valid conversion here at the type level. It's the process of evaluating the conversion, which for
// constants happens at compile time, that triggers the error.
HashSet<DiagnosticInfo> unused = null;
var bag = DiagnosticBag.GetInstance();
var nullableIntType = compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(compilation.GetSpecialType(SpecialType.System_Int32));
var conversion = compilation.Conversions.ClassifyConversionFromExpression(
compilation.GetBinder(target).BindExpression(operand, bag),
nullableIntType,
ref unused);
Assert.True(conversion.IsExplicit && conversion.IsNullable);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Tools/BuildValidator/Program.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Rebuild;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace BuildValidator
{
/// <summary>
/// Build Validator enumerates the output of the Roslyn build, extracts the compilation options
/// from the PE and attempts to rebuild the source using that information. It then checks
/// that the new build output is the same as the original build
/// </summary>
internal class Program
{
internal const int ExitSuccess = 0;
internal const int ExitFailure = 1;
static int Main(string[] args)
{
System.Diagnostics.Trace.Listeners.Clear();
var rootCommand = new RootCommand
{
new Option<string>(
"--assembliesPath", BuildValidatorResources.Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times
) { IsRequired = true, Argument = { Arity = ArgumentArity.OneOrMore } },
new Option<string>(
"--exclude", BuildValidatorResources.Assemblies_to_be_excluded_substring_match
) { Argument = { Arity = ArgumentArity.ZeroOrMore } },
new Option<string>(
"--sourcePath", BuildValidatorResources.Path_to_sources_to_use_in_rebuild
) { IsRequired = true },
new Option<string>(
"--referencesPath", BuildValidatorResources.Path_to_referenced_assemblies_can_be_specified_zero_or_more_times
) { Argument = { Arity = ArgumentArity.ZeroOrMore } },
new Option<bool>(
"--verbose", BuildValidatorResources.Output_verbose_log_information
),
new Option<bool>(
"--quiet", BuildValidatorResources.Do_not_output_log_information_to_console
),
new Option<bool>(
"--debug", BuildValidatorResources.Output_debug_info_when_rebuild_is_not_equal_to_the_original
),
new Option<string?>(
"--debugPath", BuildValidatorResources.Path_to_output_debug_info
)
};
rootCommand.Handler = CommandHandler.Create(new Func<string[], string[]?, string, string[]?, bool, bool, bool, string, int>(HandleCommand));
return rootCommand.Invoke(args);
}
static int HandleCommand(string[] assembliesPath, string[]? exclude, string sourcePath, string[]? referencesPath, bool verbose, bool quiet, bool debug, string? debugPath)
{
// If user provided a debug path then assume we should write debug outputs.
debug |= debugPath is object;
debugPath ??= Path.Combine(Path.GetTempPath(), $"BuildValidator");
referencesPath ??= Array.Empty<string>();
var excludes = new List<string>(exclude ?? Array.Empty<string>());
excludes.Add(Path.DirectorySeparatorChar + "runtimes" + Path.DirectorySeparatorChar);
excludes.Add(Path.DirectorySeparatorChar + "ref" + Path.DirectorySeparatorChar);
excludes.Add(@".resources.dll");
var options = new Options(assembliesPath, referencesPath, excludes.ToArray(), sourcePath, verbose, quiet, debug, debugPath);
// TODO: remove the DemoLoggerProvider or convert it to something more permanent
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel((options.Verbose, options.Quiet) switch
{
(_, true) => LogLevel.Error,
(true, _) => LogLevel.Trace,
_ => LogLevel.Information
});
builder.AddProvider(new DemoLoggerProvider());
});
var logger = loggerFactory.CreateLogger<Program>();
try
{
var fullDebugPath = Path.GetFullPath(debugPath);
logger.LogInformation($@"Using debug folder: ""{fullDebugPath}""");
Directory.Delete(debugPath, recursive: true);
logger.LogInformation($@"Cleaned debug folder: ""{fullDebugPath}""");
}
catch (IOException)
{
// no-op
}
try
{
var artifactsDirs = options.AssembliesPaths.Select(path => new DirectoryInfo(path));
using (logger.BeginScope("Rebuild Search Paths"))
{
foreach (var artifactsDir in artifactsDirs)
{
logger.LogInformation($@"""{artifactsDir.FullName}""");
}
}
var assemblyInfos = GetAssemblyInfos(
options.AssembliesPaths,
options.Excludes,
logger);
logAssemblyInfos();
var success = ValidateFiles(assemblyInfos, options, loggerFactory);
Console.Out.Flush();
return success ? ExitSuccess : ExitFailure;
void logAssemblyInfos()
{
logger.LogInformation("Assemblies to be validated");
foreach (var assemblyInfo in assemblyInfos)
{
logger.LogInformation($"\t{assemblyInfo.FilePath} - {assemblyInfo.Mvid}");
}
}
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
throw;
}
}
private static AssemblyInfo[] GetAssemblyInfos(
IEnumerable<string> assemblySearchPaths,
IEnumerable<string> excludes,
ILogger logger)
{
var map = new Dictionary<Guid, AssemblyInfo>();
foreach (var directory in assemblySearchPaths)
{
foreach (var filePath in getAssemblyPaths(directory))
{
if (excludes.Any(x => filePath.IndexOf(x, FileNameEqualityComparer.StringComparison) >= 0))
{
logger.LogInformation($"Skipping excluded file {filePath}");
continue;
}
if (Util.GetPortableExecutableInfo(filePath) is not { } peInfo)
{
logger.LogError($"Skipping non-pe file {filePath}");
continue;
}
if (peInfo.IsReadyToRun)
{
logger.LogError($"Skipping ReadyToRun file {filePath}");
continue;
}
if (map.TryGetValue(peInfo.Mvid, out var assemblyInfo))
{
// It's okay for the assembly to be duplicated in the search path.
logger.LogInformation("Duplicate assembly path have same MVID");
logger.LogInformation($"\t{filePath}");
logger.LogInformation($"\t{assemblyInfo.FilePath}");
continue;
}
map[peInfo.Mvid] = new AssemblyInfo(filePath, peInfo.Mvid);
}
}
return map.Values.OrderBy(x => x.FileName, FileNameEqualityComparer.StringComparer).ToArray();
static IEnumerable<string> getAssemblyPaths(string directory)
{
var exePaths = Directory.EnumerateFiles(directory, "*.exe", SearchOption.AllDirectories);
var dllPaths = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);
return Enumerable.Concat(exePaths, dllPaths);
}
}
private static bool ValidateFiles(IEnumerable<AssemblyInfo> assemblyInfos, Options options, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger<Program>();
var referenceResolver = new LocalReferenceResolver(options, loggerFactory);
var assembliesCompiled = new List<CompilationDiff>();
foreach (var assemblyInfo in assemblyInfos)
{
var compilationDiff = ValidateFile(options, assemblyInfo, logger, referenceResolver);
assembliesCompiled.Add(compilationDiff);
if (!compilationDiff.Succeeded)
{
logger.LogError($"Validation failed for {assemblyInfo.FilePath}");
var debugPath = Path.Combine(
options.DebugPath,
assemblyInfo.TargetFramework,
Path.GetFileNameWithoutExtension(assemblyInfo.FileName));
logger.LogInformation($@"Writing diffs to ""{Path.GetFullPath(debugPath)}""");
compilationDiff.WriteArtifacts(debugPath, logger);
}
}
bool success = true;
using var summary = logger.BeginScope("Summary");
using (logger.BeginScope("Successful rebuilds"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.Success))
{
logger.LogInformation($"\t{diff.AssemblyInfo.FilePath}");
}
}
using (logger.BeginScope("Rebuilds with output differences"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.BinaryDifference))
{
logger.LogWarning($"\t{diff.AssemblyInfo.FilePath}");
success = false;
}
}
using (logger.BeginScope("Rebuilds with compilation errors"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.CompilationError))
{
logger.LogError($"\t{diff.AssemblyInfo.FilePath} had {diff.Diagnostics.Length} diagnostics.");
success = false;
}
}
using (logger.BeginScope("Rebuilds with missing references"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.MissingReferences))
{
logger.LogError($"\t{diff.AssemblyInfo.FilePath}");
success = false;
}
}
using (logger.BeginScope("Rebuilds with other issues"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.MiscError))
{
logger.LogError($"{diff.AssemblyInfo.FilePath} {diff.MiscErrorMessage}");
success = false;
}
}
return success;
}
private static CompilationDiff ValidateFile(
Options options,
AssemblyInfo assemblyInfo,
ILogger logger,
LocalReferenceResolver referenceResolver)
{
// Find the embedded pdb
using var originalPeReader = new PEReader(File.OpenRead(assemblyInfo.FilePath));
var originalBinary = new FileInfo(assemblyInfo.FilePath);
var pdbOpened = originalPeReader.TryOpenAssociatedPortablePdb(
peImagePath: assemblyInfo.FilePath,
filePath => File.Exists(filePath) ? new MemoryStream(File.ReadAllBytes(filePath)) : null,
out var pdbReaderProvider,
out var pdbPath);
if (!pdbOpened || pdbReaderProvider is null)
{
logger.LogError($"Could not find pdb for {originalBinary.FullName}");
return CompilationDiff.CreateMiscError(assemblyInfo, "Could not find pdb");
}
using var _ = logger.BeginScope($"Verifying {originalBinary.FullName} with pdb {pdbPath ?? "[embedded]"}");
var pdbReader = pdbReaderProvider.GetMetadataReader();
var optionsReader = new CompilationOptionsReader(logger, pdbReader, originalPeReader);
if (!optionsReader.HasMetadataCompilationOptions)
{
return CompilationDiff.CreateMiscError(assemblyInfo, "Missing metadata compilation options");
}
var sourceLinks = ResolveSourceLinks(optionsReader, logger);
var sourceResolver = new LocalSourceResolver(options, sourceLinks, logger);
var artifactResolver = new RebuildArtifactResolver(sourceResolver, referenceResolver);
CompilationFactory compilationFactory;
try
{
compilationFactory = CompilationFactory.Create(
originalBinary.Name,
optionsReader);
return CompilationDiff.Create(
assemblyInfo,
compilationFactory,
artifactResolver,
logger);
}
catch (Exception ex)
{
return CompilationDiff.CreateMiscError(assemblyInfo, ex.Message);
}
}
private static ImmutableArray<SourceLinkEntry> ResolveSourceLinks(CompilationOptionsReader compilationOptionsReader, ILogger logger)
{
using var _ = logger.BeginScope("Source Links");
var sourceLinkUTF8 = compilationOptionsReader.GetSourceLinkUTF8();
if (sourceLinkUTF8 is null)
{
logger.LogInformation("No source link cdi found in pdb");
return ImmutableArray<SourceLinkEntry>.Empty;
}
var parseResult = JsonConvert.DeserializeAnonymousType(Encoding.UTF8.GetString(sourceLinkUTF8), new { documents = (Dictionary<string, string>?)null });
var sourceLinks = parseResult.documents.Select(makeSourceLink).ToImmutableArray();
if (sourceLinks.IsDefault)
{
logger.LogInformation("Empty source link cdi found in pdb");
sourceLinks = ImmutableArray<SourceLinkEntry>.Empty;
}
else
{
foreach (var link in sourceLinks)
{
logger.LogInformation($@"""{link.Prefix}"": ""{link.Replace}""");
}
}
return sourceLinks;
static SourceLinkEntry makeSourceLink(KeyValuePair<string, string> entry)
{
// TODO: determine if this subsitution is correct
var (key, value) = (entry.Key, entry.Value); // TODO: use Deconstruct in .NET Core
var prefix = key.Remove(key.LastIndexOf("*"));
var replace = value.Remove(value.LastIndexOf("*"));
return new SourceLinkEntry(prefix, replace);
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Rebuild;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace BuildValidator
{
/// <summary>
/// Build Validator enumerates the output of the Roslyn build, extracts the compilation options
/// from the PE and attempts to rebuild the source using that information. It then checks
/// that the new build output is the same as the original build
/// </summary>
internal class Program
{
internal const int ExitSuccess = 0;
internal const int ExitFailure = 1;
static int Main(string[] args)
{
System.Diagnostics.Trace.Listeners.Clear();
var rootCommand = new RootCommand
{
new Option<string>(
"--assembliesPath", BuildValidatorResources.Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times
) { IsRequired = true, Argument = { Arity = ArgumentArity.OneOrMore } },
new Option<string>(
"--exclude", BuildValidatorResources.Assemblies_to_be_excluded_substring_match
) { Argument = { Arity = ArgumentArity.ZeroOrMore } },
new Option<string>(
"--sourcePath", BuildValidatorResources.Path_to_sources_to_use_in_rebuild
) { IsRequired = true },
new Option<string>(
"--referencesPath", BuildValidatorResources.Path_to_referenced_assemblies_can_be_specified_zero_or_more_times
) { Argument = { Arity = ArgumentArity.ZeroOrMore } },
new Option<bool>(
"--verbose", BuildValidatorResources.Output_verbose_log_information
),
new Option<bool>(
"--quiet", BuildValidatorResources.Do_not_output_log_information_to_console
),
new Option<bool>(
"--debug", BuildValidatorResources.Output_debug_info_when_rebuild_is_not_equal_to_the_original
),
new Option<string?>(
"--debugPath", BuildValidatorResources.Path_to_output_debug_info
)
};
rootCommand.Handler = CommandHandler.Create(new Func<string[], string[]?, string, string[]?, bool, bool, bool, string, int>(HandleCommand));
return rootCommand.Invoke(args);
}
static int HandleCommand(string[] assembliesPath, string[]? exclude, string sourcePath, string[]? referencesPath, bool verbose, bool quiet, bool debug, string? debugPath)
{
// If user provided a debug path then assume we should write debug outputs.
debug |= debugPath is object;
debugPath ??= Path.Combine(Path.GetTempPath(), $"BuildValidator");
referencesPath ??= Array.Empty<string>();
var excludes = new List<string>(exclude ?? Array.Empty<string>());
excludes.Add(Path.DirectorySeparatorChar + "runtimes" + Path.DirectorySeparatorChar);
excludes.Add(Path.DirectorySeparatorChar + "ref" + Path.DirectorySeparatorChar);
excludes.Add(@".resources.dll");
var options = new Options(assembliesPath, referencesPath, excludes.ToArray(), sourcePath, verbose, quiet, debug, debugPath);
// TODO: remove the DemoLoggerProvider or convert it to something more permanent
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel((options.Verbose, options.Quiet) switch
{
(_, true) => LogLevel.Error,
(true, _) => LogLevel.Trace,
_ => LogLevel.Information
});
builder.AddProvider(new DemoLoggerProvider());
});
var logger = loggerFactory.CreateLogger<Program>();
try
{
var fullDebugPath = Path.GetFullPath(debugPath);
logger.LogInformation($@"Using debug folder: ""{fullDebugPath}""");
Directory.Delete(debugPath, recursive: true);
logger.LogInformation($@"Cleaned debug folder: ""{fullDebugPath}""");
}
catch (IOException)
{
// no-op
}
try
{
var artifactsDirs = options.AssembliesPaths.Select(path => new DirectoryInfo(path));
using (logger.BeginScope("Rebuild Search Paths"))
{
foreach (var artifactsDir in artifactsDirs)
{
logger.LogInformation($@"""{artifactsDir.FullName}""");
}
}
var assemblyInfos = GetAssemblyInfos(
options.AssembliesPaths,
options.Excludes,
logger);
logAssemblyInfos();
var success = ValidateFiles(assemblyInfos, options, loggerFactory);
Console.Out.Flush();
return success ? ExitSuccess : ExitFailure;
void logAssemblyInfos()
{
logger.LogInformation("Assemblies to be validated");
foreach (var assemblyInfo in assemblyInfos)
{
logger.LogInformation($"\t{assemblyInfo.FilePath} - {assemblyInfo.Mvid}");
}
}
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
throw;
}
}
private static AssemblyInfo[] GetAssemblyInfos(
IEnumerable<string> assemblySearchPaths,
IEnumerable<string> excludes,
ILogger logger)
{
var map = new Dictionary<Guid, AssemblyInfo>();
foreach (var directory in assemblySearchPaths)
{
foreach (var filePath in getAssemblyPaths(directory))
{
if (excludes.Any(x => filePath.IndexOf(x, FileNameEqualityComparer.StringComparison) >= 0))
{
logger.LogInformation($"Skipping excluded file {filePath}");
continue;
}
if (Util.GetPortableExecutableInfo(filePath) is not { } peInfo)
{
logger.LogError($"Skipping non-pe file {filePath}");
continue;
}
if (peInfo.IsReadyToRun)
{
logger.LogError($"Skipping ReadyToRun file {filePath}");
continue;
}
if (map.TryGetValue(peInfo.Mvid, out var assemblyInfo))
{
// It's okay for the assembly to be duplicated in the search path.
logger.LogInformation("Duplicate assembly path have same MVID");
logger.LogInformation($"\t{filePath}");
logger.LogInformation($"\t{assemblyInfo.FilePath}");
continue;
}
map[peInfo.Mvid] = new AssemblyInfo(filePath, peInfo.Mvid);
}
}
return map.Values.OrderBy(x => x.FileName, FileNameEqualityComparer.StringComparer).ToArray();
static IEnumerable<string> getAssemblyPaths(string directory)
{
var exePaths = Directory.EnumerateFiles(directory, "*.exe", SearchOption.AllDirectories);
var dllPaths = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);
return Enumerable.Concat(exePaths, dllPaths);
}
}
private static bool ValidateFiles(IEnumerable<AssemblyInfo> assemblyInfos, Options options, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger<Program>();
var referenceResolver = new LocalReferenceResolver(options, loggerFactory);
var assembliesCompiled = new List<CompilationDiff>();
foreach (var assemblyInfo in assemblyInfos)
{
var compilationDiff = ValidateFile(options, assemblyInfo, logger, referenceResolver);
assembliesCompiled.Add(compilationDiff);
if (!compilationDiff.Succeeded)
{
logger.LogError($"Validation failed for {assemblyInfo.FilePath}");
var debugPath = Path.Combine(
options.DebugPath,
assemblyInfo.TargetFramework,
Path.GetFileNameWithoutExtension(assemblyInfo.FileName));
logger.LogInformation($@"Writing diffs to ""{Path.GetFullPath(debugPath)}""");
compilationDiff.WriteArtifacts(debugPath, logger);
}
}
bool success = true;
using var summary = logger.BeginScope("Summary");
using (logger.BeginScope("Successful rebuilds"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.Success))
{
logger.LogInformation($"\t{diff.AssemblyInfo.FilePath}");
}
}
using (logger.BeginScope("Rebuilds with output differences"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.BinaryDifference))
{
logger.LogWarning($"\t{diff.AssemblyInfo.FilePath}");
success = false;
}
}
using (logger.BeginScope("Rebuilds with compilation errors"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.CompilationError))
{
logger.LogError($"\t{diff.AssemblyInfo.FilePath} had {diff.Diagnostics.Length} diagnostics.");
success = false;
}
}
using (logger.BeginScope("Rebuilds with missing references"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.MissingReferences))
{
logger.LogError($"\t{diff.AssemblyInfo.FilePath}");
success = false;
}
}
using (logger.BeginScope("Rebuilds with other issues"))
{
foreach (var diff in assembliesCompiled.Where(a => a.Result == RebuildResult.MiscError))
{
logger.LogError($"{diff.AssemblyInfo.FilePath} {diff.MiscErrorMessage}");
success = false;
}
}
return success;
}
private static CompilationDiff ValidateFile(
Options options,
AssemblyInfo assemblyInfo,
ILogger logger,
LocalReferenceResolver referenceResolver)
{
// Find the embedded pdb
using var originalPeReader = new PEReader(File.OpenRead(assemblyInfo.FilePath));
var originalBinary = new FileInfo(assemblyInfo.FilePath);
var pdbOpened = originalPeReader.TryOpenAssociatedPortablePdb(
peImagePath: assemblyInfo.FilePath,
filePath => File.Exists(filePath) ? new MemoryStream(File.ReadAllBytes(filePath)) : null,
out var pdbReaderProvider,
out var pdbPath);
if (!pdbOpened || pdbReaderProvider is null)
{
logger.LogError($"Could not find pdb for {originalBinary.FullName}");
return CompilationDiff.CreateMiscError(assemblyInfo, "Could not find pdb");
}
using var _ = logger.BeginScope($"Verifying {originalBinary.FullName} with pdb {pdbPath ?? "[embedded]"}");
var pdbReader = pdbReaderProvider.GetMetadataReader();
var optionsReader = new CompilationOptionsReader(logger, pdbReader, originalPeReader);
if (!optionsReader.HasMetadataCompilationOptions)
{
return CompilationDiff.CreateMiscError(assemblyInfo, "Missing metadata compilation options");
}
var sourceLinks = ResolveSourceLinks(optionsReader, logger);
var sourceResolver = new LocalSourceResolver(options, sourceLinks, logger);
var artifactResolver = new RebuildArtifactResolver(sourceResolver, referenceResolver);
CompilationFactory compilationFactory;
try
{
compilationFactory = CompilationFactory.Create(
originalBinary.Name,
optionsReader);
return CompilationDiff.Create(
assemblyInfo,
compilationFactory,
artifactResolver,
logger);
}
catch (Exception ex)
{
return CompilationDiff.CreateMiscError(assemblyInfo, ex.Message);
}
}
private static ImmutableArray<SourceLinkEntry> ResolveSourceLinks(CompilationOptionsReader compilationOptionsReader, ILogger logger)
{
using var _ = logger.BeginScope("Source Links");
var sourceLinkUTF8 = compilationOptionsReader.GetSourceLinkUTF8();
if (sourceLinkUTF8 is null)
{
logger.LogInformation("No source link cdi found in pdb");
return ImmutableArray<SourceLinkEntry>.Empty;
}
var parseResult = JsonConvert.DeserializeAnonymousType(Encoding.UTF8.GetString(sourceLinkUTF8), new { documents = (Dictionary<string, string>?)null });
var sourceLinks = parseResult.documents.Select(makeSourceLink).ToImmutableArray();
if (sourceLinks.IsDefault)
{
logger.LogInformation("Empty source link cdi found in pdb");
sourceLinks = ImmutableArray<SourceLinkEntry>.Empty;
}
else
{
foreach (var link in sourceLinks)
{
logger.LogInformation($@"""{link.Prefix}"": ""{link.Replace}""");
}
}
return sourceLinks;
static SourceLinkEntry makeSourceLink(KeyValuePair<string, string> entry)
{
// TODO: determine if this subsitution is correct
var (key, value) = (entry.Key, entry.Value); // TODO: use Deconstruct in .NET Core
var prefix = key.Remove(key.LastIndexOf("*"));
var replace = value.Remove(value.LastIndexOf("*"));
return new SourceLinkEntry(prefix, replace);
}
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/Core/MSBuild/MSBuild/DiagnosticReportingOptions.cs | // Licensed to the .NET Foundation under one or more 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.MSBuild
{
internal readonly struct DiagnosticReportingOptions
{
public DiagnosticReportingMode OnPathFailure { get; }
public DiagnosticReportingMode OnLoaderFailure { get; }
public DiagnosticReportingOptions(
DiagnosticReportingMode onPathFailure,
DiagnosticReportingMode onLoaderFailure)
{
OnPathFailure = onPathFailure;
OnLoaderFailure = onLoaderFailure;
}
public static DiagnosticReportingOptions IgnoreAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Ignore, DiagnosticReportingMode.Ignore);
public static DiagnosticReportingOptions ThrowForAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Throw, DiagnosticReportingMode.Throw);
}
}
| // Licensed to the .NET Foundation under one or more 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.MSBuild
{
internal readonly struct DiagnosticReportingOptions
{
public DiagnosticReportingMode OnPathFailure { get; }
public DiagnosticReportingMode OnLoaderFailure { get; }
public DiagnosticReportingOptions(
DiagnosticReportingMode onPathFailure,
DiagnosticReportingMode onLoaderFailure)
{
OnPathFailure = onPathFailure;
OnLoaderFailure = onLoaderFailure;
}
public static DiagnosticReportingOptions IgnoreAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Ignore, DiagnosticReportingMode.Ignore);
public static DiagnosticReportingOptions ThrowForAll { get; }
= new DiagnosticReportingOptions(DiagnosticReportingMode.Throw, DiagnosticReportingMode.Throw);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/OrderableMetadata.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal class OrderableMetadata
{
[DefaultValue(new string[] { })]
public object? After { get; }
[DefaultValue(new string[] { })]
public object? Before { get; }
internal IEnumerable<string> AfterTyped { get; set; }
internal IEnumerable<string> BeforeTyped { get; set; }
public string? Name { get; }
public OrderableMetadata(IDictionary<string, object> data)
{
var readOnlyData = (IReadOnlyDictionary<string, object>)data;
this.AfterTyped = readOnlyData.GetEnumerableMetadata<string>("After").WhereNotNull();
this.BeforeTyped = readOnlyData.GetEnumerableMetadata<string>("Before").WhereNotNull();
this.Name = (string?)data.GetValueOrDefault("Name");
}
public OrderableMetadata(string? name, IEnumerable<string>? after = null, IEnumerable<string>? before = null)
{
this.AfterTyped = after ?? SpecializedCollections.EmptyEnumerable<string>();
this.BeforeTyped = before ?? SpecializedCollections.EmptyEnumerable<string>();
this.Name = 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.Collections.Generic;
using System.ComponentModel;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal class OrderableMetadata
{
[DefaultValue(new string[] { })]
public object? After { get; }
[DefaultValue(new string[] { })]
public object? Before { get; }
internal IEnumerable<string> AfterTyped { get; set; }
internal IEnumerable<string> BeforeTyped { get; set; }
public string? Name { get; }
public OrderableMetadata(IDictionary<string, object> data)
{
var readOnlyData = (IReadOnlyDictionary<string, object>)data;
this.AfterTyped = readOnlyData.GetEnumerableMetadata<string>("After").WhereNotNull();
this.BeforeTyped = readOnlyData.GetEnumerableMetadata<string>("Before").WhereNotNull();
this.Name = (string?)data.GetValueOrDefault("Name");
}
public OrderableMetadata(string? name, IEnumerable<string>? after = null, IEnumerable<string>? before = null)
{
this.AfterTyped = after ?? SpecializedCollections.EmptyEnumerable<string>();
this.BeforeTyped = before ?? SpecializedCollections.EmptyEnumerable<string>();
this.Name = name;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Portable/Syntax/DoStatementSyntax.cs | // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class DoStatementSyntax
{
public DoStatementSyntax Update(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken)
=> Update(AttributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static DoStatementSyntax DoStatement(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken)
=> DoStatement(attributeLists: default, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken);
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class DoStatementSyntax
{
public DoStatementSyntax Update(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken)
=> Update(AttributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static DoStatementSyntax DoStatement(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken)
=> DoStatement(attributeLists: default, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/Core/Portable/Operations/PlaceholderKind.cs | // Licensed to the .NET Foundation under one or more 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.Operations
{
internal enum PlaceholderKind
{
Unspecified = 0,
SwitchOperationExpression = 1,
ForToLoopBinaryOperatorLeftOperand = 2,
ForToLoopBinaryOperatorRightOperand = 3,
AggregationGroup = 4,
}
}
| // Licensed to the .NET Foundation under one or more 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.Operations
{
internal enum PlaceholderKind
{
Unspecified = 0,
SwitchOperationExpression = 1,
ForToLoopBinaryOperatorLeftOperand = 2,
ForToLoopBinaryOperatorRightOperand = 3,
AggregationGroup = 4,
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Scripting/CoreTestUtilities/TestConsoleIO.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Text;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting.Test
{
internal sealed class TestConsoleIO : ConsoleIO
{
private const ConsoleColor InitialColor = ConsoleColor.Gray;
public TestConsoleIO(string input)
: this(new Reader(input))
{
}
private TestConsoleIO(Reader reader)
: this(reader, new Writer(reader))
{
}
private TestConsoleIO(Reader reader, TextWriter output)
: base(output: output, error: new TeeWriter(output), input: reader)
{
}
public override void SetForegroundColor(ConsoleColor consoleColor) => ((Writer)Out).CurrentColor = consoleColor;
public override void ResetColor() => SetForegroundColor(InitialColor);
private sealed class Reader : StringReader
{
public readonly StringBuilder ContentRead = new StringBuilder();
public Reader(string input)
: base(input)
{
}
public override string ReadLine()
{
string result = base.ReadLine();
ContentRead.AppendLine(result);
return result;
}
}
private sealed class Writer : StringWriter
{
private ConsoleColor _lastColor = InitialColor;
public ConsoleColor CurrentColor = InitialColor;
public override Encoding Encoding => Encoding.UTF8;
private readonly Reader _reader;
public Writer(Reader reader)
{
_reader = reader;
}
private void OnBeforeWrite()
{
if (_reader.ContentRead.Length > 0)
{
GetStringBuilder().Append(_reader.ContentRead.ToString());
_reader.ContentRead.Clear();
}
if (_lastColor != CurrentColor)
{
GetStringBuilder().AppendLine($"«{CurrentColor}»");
_lastColor = CurrentColor;
}
}
public override void Write(char value)
{
OnBeforeWrite();
base.Write(value);
}
public override void Write(string value)
{
OnBeforeWrite();
GetStringBuilder().Append(value);
}
public override void WriteLine(string value)
{
OnBeforeWrite();
GetStringBuilder().AppendLine(value);
}
public override void WriteLine()
{
OnBeforeWrite();
GetStringBuilder().AppendLine();
}
}
private sealed class TeeWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
private readonly TextWriter _other;
public TeeWriter(TextWriter other)
{
_other = other;
}
public override void Write(char value)
{
_other.Write(value);
GetStringBuilder().Append(value);
}
public override void Write(string value)
{
_other.Write(value);
GetStringBuilder().Append(value);
}
public override void WriteLine(string value)
{
_other.WriteLine(value);
GetStringBuilder().AppendLine(value);
}
public override void WriteLine()
{
_other.WriteLine();
GetStringBuilder().AppendLine();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Text;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting.Test
{
internal sealed class TestConsoleIO : ConsoleIO
{
private const ConsoleColor InitialColor = ConsoleColor.Gray;
public TestConsoleIO(string input)
: this(new Reader(input))
{
}
private TestConsoleIO(Reader reader)
: this(reader, new Writer(reader))
{
}
private TestConsoleIO(Reader reader, TextWriter output)
: base(output: output, error: new TeeWriter(output), input: reader)
{
}
public override void SetForegroundColor(ConsoleColor consoleColor) => ((Writer)Out).CurrentColor = consoleColor;
public override void ResetColor() => SetForegroundColor(InitialColor);
private sealed class Reader : StringReader
{
public readonly StringBuilder ContentRead = new StringBuilder();
public Reader(string input)
: base(input)
{
}
public override string ReadLine()
{
string result = base.ReadLine();
ContentRead.AppendLine(result);
return result;
}
}
private sealed class Writer : StringWriter
{
private ConsoleColor _lastColor = InitialColor;
public ConsoleColor CurrentColor = InitialColor;
public override Encoding Encoding => Encoding.UTF8;
private readonly Reader _reader;
public Writer(Reader reader)
{
_reader = reader;
}
private void OnBeforeWrite()
{
if (_reader.ContentRead.Length > 0)
{
GetStringBuilder().Append(_reader.ContentRead.ToString());
_reader.ContentRead.Clear();
}
if (_lastColor != CurrentColor)
{
GetStringBuilder().AppendLine($"«{CurrentColor}»");
_lastColor = CurrentColor;
}
}
public override void Write(char value)
{
OnBeforeWrite();
base.Write(value);
}
public override void Write(string value)
{
OnBeforeWrite();
GetStringBuilder().Append(value);
}
public override void WriteLine(string value)
{
OnBeforeWrite();
GetStringBuilder().AppendLine(value);
}
public override void WriteLine()
{
OnBeforeWrite();
GetStringBuilder().AppendLine();
}
}
private sealed class TeeWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
private readonly TextWriter _other;
public TeeWriter(TextWriter other)
{
_other = other;
}
public override void Write(char value)
{
_other.Write(value);
GetStringBuilder().Append(value);
}
public override void Write(string value)
{
_other.Write(value);
GetStringBuilder().Append(value);
}
public override void WriteLine(string value)
{
_other.WriteLine(value);
GetStringBuilder().AppendLine(value);
}
public override void WriteLine()
{
_other.WriteLine();
GetStringBuilder().AppendLine();
}
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/CSharp/Test/ProjectSystemShim/CPS/CSharpReferencesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS
{
using static CSharpHelpers;
[UseExportProvider]
public class CSharpReferenceTests
{
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task AddRemoveProjectAndMetadataReference_CPS()
{
using var environment = new TestEnvironment();
var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
var project2 = await CreateCSharpCPSProjectAsync(environment, "project2", commandLineArguments: @"/out:c:\project2.dll");
var project3 = await CreateCSharpCPSProjectAsync(environment, "project3", commandLineArguments: @"/out:c:\project3.dll");
var project4 = await CreateCSharpCPSProjectAsync(environment, "project4");
// Add project reference
project3.AddProjectReference(project1, new MetadataReferenceProperties());
// Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
project3.AddMetadataReference(@"c:\project2.dll", new MetadataReferenceProperties());
// Add project reference with no output path
project3.AddProjectReference(project4, new MetadataReferenceProperties());
// Add metadata reference
var metadaRefFilePath = @"c:\someAssembly.dll";
project3.AddMetadataReference(metadaRefFilePath, new MetadataReferenceProperties(embedInteropTypes: true));
IEnumerable<ProjectReference> GetProject3ProjectReferences()
{
return environment.Workspace
.CurrentSolution.GetProject(project3.Id).ProjectReferences;
}
IEnumerable<PortableExecutableReference> GetProject3MetadataReferences()
{
return environment.Workspace.CurrentSolution.GetProject(project3.Id)
.MetadataReferences
.Cast<PortableExecutableReference>();
}
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id));
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id));
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id));
Assert.True(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath));
// Change output path for project reference and verify the reference.
((IWorkspaceProjectContext)project4).BinOutputPath = @"C:\project4.dll";
Assert.Equal(@"C:\project4.dll", project4.BinOutputPath);
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id));
// Remove project reference
project3.RemoveProjectReference(project1);
// Remove project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
project3.RemoveMetadataReference(@"c:\project2.dll");
// Remove metadata reference
project3.RemoveMetadataReference(metadaRefFilePath);
Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id));
Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id));
Assert.False(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath));
project1.Dispose();
project2.Dispose();
project4.Dispose();
project3.Dispose();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task RemoveProjectConvertsProjectReferencesBack()
{
using var environment = new TestEnvironment();
var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
var project2 = await CreateCSharpCPSProjectAsync(environment, "project2");
// Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
project2.AddMetadataReference(@"c:\project1.dll", new MetadataReferenceProperties());
Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences);
// Remove project1. project2's reference should have been converted back
project1.Dispose();
Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences);
Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).MetadataReferences);
project2.Dispose();
}
[WpfFact]
[WorkItem(461967, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/461967")]
[WorkItem(727173, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/727173")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task AddingMetadataReferenceToProjectThatCannotCompileInTheIdeKeepsMetadataReference()
{
using var environment = new TestEnvironment(typeof(NoCompilationLanguageServiceFactory));
var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
var project2 = await CreateNonCompilableProjectAsync(environment, "project2", @"C:\project2.fsproj");
project2.BinOutputPath = "c:\\project2.dll";
project1.AddMetadataReference(project2.BinOutputPath, MetadataReferenceProperties.Assembly);
// We should not have converted that to a project reference, because we would have no way to produce the compilation
Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project1.Id).AllProjectReferences);
project2.Dispose();
project1.Dispose();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task AddRemoveAnalyzerReference_CPS()
{
using var environment = new TestEnvironment();
using var project = await CreateCSharpCPSProjectAsync(environment, "project1");
// Add analyzer reference
using var tempRoot = new TempRoot();
var analyzerAssemblyFullPath = tempRoot.CreateFile().Path;
bool AnalyzersContainsAnalyzer()
{
return environment.Workspace.CurrentSolution.Projects.Single()
.AnalyzerReferences.Cast<AnalyzerReference>()
.Any(a => a.FullPath == analyzerAssemblyFullPath);
}
project.AddAnalyzerReference(analyzerAssemblyFullPath);
Assert.True(AnalyzersContainsAnalyzer());
// Remove analyzer reference
project.RemoveAnalyzerReference(analyzerAssemblyFullPath);
Assert.False(AnalyzersContainsAnalyzer());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS
{
using static CSharpHelpers;
[UseExportProvider]
public class CSharpReferenceTests
{
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task AddRemoveProjectAndMetadataReference_CPS()
{
using var environment = new TestEnvironment();
var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
var project2 = await CreateCSharpCPSProjectAsync(environment, "project2", commandLineArguments: @"/out:c:\project2.dll");
var project3 = await CreateCSharpCPSProjectAsync(environment, "project3", commandLineArguments: @"/out:c:\project3.dll");
var project4 = await CreateCSharpCPSProjectAsync(environment, "project4");
// Add project reference
project3.AddProjectReference(project1, new MetadataReferenceProperties());
// Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
project3.AddMetadataReference(@"c:\project2.dll", new MetadataReferenceProperties());
// Add project reference with no output path
project3.AddProjectReference(project4, new MetadataReferenceProperties());
// Add metadata reference
var metadaRefFilePath = @"c:\someAssembly.dll";
project3.AddMetadataReference(metadaRefFilePath, new MetadataReferenceProperties(embedInteropTypes: true));
IEnumerable<ProjectReference> GetProject3ProjectReferences()
{
return environment.Workspace
.CurrentSolution.GetProject(project3.Id).ProjectReferences;
}
IEnumerable<PortableExecutableReference> GetProject3MetadataReferences()
{
return environment.Workspace.CurrentSolution.GetProject(project3.Id)
.MetadataReferences
.Cast<PortableExecutableReference>();
}
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id));
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id));
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id));
Assert.True(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath));
// Change output path for project reference and verify the reference.
((IWorkspaceProjectContext)project4).BinOutputPath = @"C:\project4.dll";
Assert.Equal(@"C:\project4.dll", project4.BinOutputPath);
Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id));
// Remove project reference
project3.RemoveProjectReference(project1);
// Remove project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
project3.RemoveMetadataReference(@"c:\project2.dll");
// Remove metadata reference
project3.RemoveMetadataReference(metadaRefFilePath);
Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id));
Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id));
Assert.False(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath));
project1.Dispose();
project2.Dispose();
project4.Dispose();
project3.Dispose();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task RemoveProjectConvertsProjectReferencesBack()
{
using var environment = new TestEnvironment();
var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
var project2 = await CreateCSharpCPSProjectAsync(environment, "project2");
// Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
project2.AddMetadataReference(@"c:\project1.dll", new MetadataReferenceProperties());
Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences);
// Remove project1. project2's reference should have been converted back
project1.Dispose();
Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences);
Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).MetadataReferences);
project2.Dispose();
}
[WpfFact]
[WorkItem(461967, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/461967")]
[WorkItem(727173, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/727173")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task AddingMetadataReferenceToProjectThatCannotCompileInTheIdeKeepsMetadataReference()
{
using var environment = new TestEnvironment(typeof(NoCompilationLanguageServiceFactory));
var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
var project2 = await CreateNonCompilableProjectAsync(environment, "project2", @"C:\project2.fsproj");
project2.BinOutputPath = "c:\\project2.dll";
project1.AddMetadataReference(project2.BinOutputPath, MetadataReferenceProperties.Assembly);
// We should not have converted that to a project reference, because we would have no way to produce the compilation
Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project1.Id).AllProjectReferences);
project2.Dispose();
project1.Dispose();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task AddRemoveAnalyzerReference_CPS()
{
using var environment = new TestEnvironment();
using var project = await CreateCSharpCPSProjectAsync(environment, "project1");
// Add analyzer reference
using var tempRoot = new TempRoot();
var analyzerAssemblyFullPath = tempRoot.CreateFile().Path;
bool AnalyzersContainsAnalyzer()
{
return environment.Workspace.CurrentSolution.Projects.Single()
.AnalyzerReferences.Cast<AnalyzerReference>()
.Any(a => a.FullPath == analyzerAssemblyFullPath);
}
project.AddAnalyzerReference(analyzerAssemblyFullPath);
Assert.True(AnalyzersContainsAnalyzer());
// Remove analyzer reference
project.RemoveAnalyzerReference(analyzerAssemblyFullPath);
Assert.False(AnalyzersContainsAnalyzer());
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo
{
[UseExportProvider]
public abstract class AbstractNavigateToTests
{
protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures;
protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory));
protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory));
protected INavigateToItemProvider _provider;
protected NavigateToTestAggregator _aggregator;
internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty);
protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider);
protected abstract string Language { get; }
public enum Composition
{
Default,
FirstVisible,
FirstActiveAndVisible,
}
protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
private async Task TestAsync(
string content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
protected async Task TestAsync(
XElement content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
private protected TestWorkspace CreateWorkspace(
XElement workspaceElement,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
private protected TestWorkspace CreateWorkspace(
string content,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = CreateWorkspace(content, exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
internal void InitializeWorkspace(TestWorkspace workspace)
{
_provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>());
_aggregator = new NavigateToTestAggregator(_provider);
}
protected static void VerifyNavigateToResultItems(
List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (var i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind));
Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive));
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
internal void VerifyNavigateToResultItem(
NavigateToItem result, string name, string displayMarkup,
PatternMatchKind matchKind, string navigateToItemKind,
Glyph glyph, string additionalInfo = null)
{
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.PatternMatch.Kind);
Assert.Equal(this.Language, result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
MarkupTestFile.GetSpans(displayMarkup, out displayMarkup,
out ImmutableArray<TextSpan> expectedDisplayNameSpans);
var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result);
Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker());
Assert.Equal(displayMarkup, itemDisplay.Name);
Assert.Equal<TextSpan>(
expectedDisplayNameSpans,
itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray());
if (additionalInfo != null)
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
}
internal static BitmapSource CreateIconBitmapSource()
{
var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
=> ComparerWithState.CompareTo(a, b, s_comparisonComponents);
private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents =
ImmutableArray.Create<Func<NavigateToItem, IComparable>>(
item => (int)item.PatternMatch.Kind,
item => item.Name,
item => item.Kind,
item => item.SecondarySort);
private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> null;
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> _workspace.CurrentSolution.Projects.First().DocumentIds.First();
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsActiveAndVisibleDocumentTrackingService(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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo
{
[UseExportProvider]
public abstract class AbstractNavigateToTests
{
protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures;
protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory));
protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory));
protected INavigateToItemProvider _provider;
protected NavigateToTestAggregator _aggregator;
internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty);
protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider);
protected abstract string Language { get; }
public enum Composition
{
Default,
FirstVisible,
FirstActiveAndVisible,
}
protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
private async Task TestAsync(
string content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
protected async Task TestAsync(
XElement content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
private protected TestWorkspace CreateWorkspace(
XElement workspaceElement,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
private protected TestWorkspace CreateWorkspace(
string content,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = CreateWorkspace(content, exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
internal void InitializeWorkspace(TestWorkspace workspace)
{
_provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>());
_aggregator = new NavigateToTestAggregator(_provider);
}
protected static void VerifyNavigateToResultItems(
List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (var i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind));
Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive));
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
internal void VerifyNavigateToResultItem(
NavigateToItem result, string name, string displayMarkup,
PatternMatchKind matchKind, string navigateToItemKind,
Glyph glyph, string additionalInfo = null)
{
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.PatternMatch.Kind);
Assert.Equal(this.Language, result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
MarkupTestFile.GetSpans(displayMarkup, out displayMarkup,
out ImmutableArray<TextSpan> expectedDisplayNameSpans);
var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result);
Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker());
Assert.Equal(displayMarkup, itemDisplay.Name);
Assert.Equal<TextSpan>(
expectedDisplayNameSpans,
itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray());
if (additionalInfo != null)
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
}
internal static BitmapSource CreateIconBitmapSource()
{
var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
=> ComparerWithState.CompareTo(a, b, s_comparisonComponents);
private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents =
ImmutableArray.Create<Func<NavigateToItem, IComparable>>(
item => (int)item.PatternMatch.Kind,
item => item.Name,
item => item.Kind,
item => item.SecondarySort);
private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> null;
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> _workspace.CurrentSolution.Projects.First().DocumentIds.First();
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsActiveAndVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/Core/Portable/LinkedFileDiffMerging/IMergeConflictHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal interface IMergeConflictHandler
{
IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal interface IMergeConflictHandler
{
IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/Test/Core/FX/RegexExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Text.RegularExpressions;
namespace Roslyn.Test.Utilities
{
public static class RegexExtensions
{
public static IEnumerable<Match> ToEnumerable(this MatchCollection collection)
{
foreach (Match m in collection)
{
yield return m;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Roslyn.Test.Utilities
{
public static class RegexExtensions
{
public static IEnumerable<Match> ToEnumerable(this MatchCollection collection)
{
foreach (Match m in collection)
{
yield return m;
}
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/CSharpTest/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_ReferenceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Text.RegularExpressions;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions
{
// All these tests came from the example at:
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference
public partial class CSharpRegexParserTests
{
[Fact]
public void ReferenceTest0()
{
Test(@"@""[aeiou]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>aeiou</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""[aeiou]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest1()
{
Test(@"@""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""nextWord"">nextWord</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..68)"" Text=""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)"" />
<Capture Name=""1"" Span=""[10..31)"" Text=""(?<duplicateWord>\w+)"" />
<Capture Name=""2"" Span=""[52..68)"" Text=""(?<nextWord>\w+)"" />
<Capture Name=""duplicateWord"" Span=""[10..31)"" Text=""(?<duplicateWord>\w+)"" />
<Capture Name=""nextWord"" Span=""[52..68)"" Text=""(?<nextWord>\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest2()
{
Test(@"@""((?<One>abc)\d+)?(?<Two>xyz)(.*)""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""One"">One</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>abc</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""Two"">Two</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>xyz</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""((?<One>abc)\d+)?(?<Two>xyz)(.*)"" />
<Capture Name=""1"" Span=""[10..26)"" Text=""((?<One>abc)\d+)"" />
<Capture Name=""2"" Span=""[38..42)"" Text=""(.*)"" />
<Capture Name=""3"" Span=""[11..22)"" Text=""(?<One>abc)"" />
<Capture Name=""4"" Span=""[27..38)"" Text=""(?<Two>xyz)"" />
<Capture Name=""One"" Span=""[11..22)"" Text=""(?<One>abc)"" />
<Capture Name=""Two"" Span=""[27..38)"" Text=""(?<Two>xyz)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest3()
{
Test(@"@""(\w+)\s(\1)""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""(\w+)\s(\1)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[17..21)"" Text=""(\1)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest4()
{
Test(@"@""\Bqu\w+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>B</TextToken>
</AnchorEscape>
<Text>
<TextToken>qu</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\Bqu\w+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest5()
{
Test(@"@""\bare\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>are</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""\bare\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest6()
{
Test(@"@""\G(\w+\s?\w*),?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>G</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""\G(\w+\s?\w*),?"" />
<Capture Name=""1"" Span=""[12..23)"" Text=""(\w+\s?\w*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest7()
{
Test(@"@""\D+(?<digit>\d+)\D+(?<digit>\d+)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""digit"">digit</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""digit"">digit</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""\D+(?<digit>\d+)\D+(?<digit>\d+)?"" />
<Capture Name=""1"" Span=""[13..26)"" Text=""(?<digit>\d+)"" />
<Capture Name=""digit"" Span=""[13..26)"" Text=""(?<digit>\d+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest8()
{
Test(@"@""(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>-</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>&#124;present</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..46)"" Text=""(\s\d{4}(-(\d{4}&#124;present))?,?)+"" />
<Capture Name=""1"" Span=""[10..45)"" Text=""(\s\d{4}(-(\d{4}&#124;present))?,?)"" />
<Capture Name=""2"" Span=""[18..41)"" Text=""(-(\d{4}&#124;present))"" />
<Capture Name=""3"" Span=""[20..40)"" Text=""(\d{4}&#124;present)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest9()
{
Test(@"@""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OpenRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>,</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>,</TextToken>
</Text>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>-</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>present</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..72)"" Text=""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"" />
<Capture Name=""1"" Span=""[11..27)"" Text=""((\w+(\s?)){2,})"" />
<Capture Name=""2"" Span=""[12..22)"" Text=""(\w+(\s?))"" />
<Capture Name=""3"" Span=""[16..21)"" Text=""(\s?)"" />
<Capture Name=""4"" Span=""[30..40)"" Text=""(\w+\s\w+)"" />
<Capture Name=""5"" Span=""[41..71)"" Text=""(\s\d{4}(-(\d{4}|present))?,?)"" />
<Capture Name=""6"" Span=""[49..67)"" Text=""(-(\d{4}|present))"" />
<Capture Name=""7"" Span=""[51..66)"" Text=""(\d{4}|present)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest10()
{
Test(@"@""^[0-9-[2468]]+$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>2468</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""^[0-9-[2468]]+$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest11()
{
Test(@"@""[a-z-[0-9]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[0-9]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest12()
{
Test(@"@""[\p{IsBasicLatin}-[\x00-\x7F]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>00</TextToken>
</HexEscape>
<MinusToken>-</MinusToken>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>7F</TextToken>
</HexEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""[\p{IsBasicLatin}-[\x00-\x7F]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest13()
{
Test(@"@""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>0000</TextToken>
</UnicodeEscape>
<MinusToken>-</MinusToken>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>FFFF</TextToken>
</UnicodeEscape>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsGreek</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>85</TextToken>
</HexEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..50)"" Text=""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest14()
{
Test(@"@""[a-z-[d-w-[m-o]]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>d</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>w</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>m</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>o</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""[a-z-[d-w-[m-o]]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest15()
{
Test(@"@""((\w+(\s?)){2,}""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OpenRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}}</CloseBraceToken>
</OpenRangeNumericQuantifier>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[25..25)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" />
<Capture Name=""1"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" />
<Capture Name=""2"" Span=""[11..21)"" Text=""(\w+(\s?))"" />
<Capture Name=""3"" Span=""[15..20)"" Text=""(\s?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest16()
{
Test(@"@""[a-z-[djp]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>djp</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[djp]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest17()
{
Test(@"@""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken><</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<CloseParenToken>)</CloseParenToken>
<Sequence>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</NegativeLookaheadGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..78)"" Text=""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$"" />
<Capture Name=""1"" Span=""[17..63)"" Text=""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)"" />
<Capture Name=""2"" Span=""[18..36)"" Text=""((?'Open'<)[^<>]*)"" />
<Capture Name=""3"" Span=""[37..61)"" Text=""((?'Close-Open'>)[^<>]*)"" />
<Capture Name=""4"" Span=""[19..29)"" Text=""(?'Open'<)"" />
<Capture Name=""5"" Span=""[38..54)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[38..54)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Open"" Span=""[19..29)"" Text=""(?'Open'<)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest18()
{
Test(@"@""((?'Close-Open'>)[^<>]*)+""", $@"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[20..24)"" Text=""Open"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..35)"" Text=""((?'Close-Open'>)[^<>]*)+"" />
<Capture Name=""1"" Span=""[10..34)"" Text=""((?'Close-Open'>)[^<>]*)"" />
<Capture Name=""2"" Span=""[11..27)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[11..27)"" Text=""(?'Close-Open'>)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest19()
{
Test(@"@""(\w)\1+.\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest20()
{
Test(@"@""\d{4}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\d{4}\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest21()
{
Test(@"@""\d{1,2},""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\d{1,2},"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest22()
{
Test(@"@""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegativeLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<ExclamationToken>!</ExclamationToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>Saturday</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>Sunday</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken> </TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NegativeLookbehindGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<Text>
<TextToken>, </TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..55)"" Text=""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"" />
<Capture Name=""1"" Span=""[14..31)"" Text=""(Saturday|Sunday)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest23()
{
Test(@"@""(?<=\b20)\d{2}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<EqualsToken>=</EqualsToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>20</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</PositiveLookbehindGrouping>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(?<=\b20)\d{2}\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest24()
{
Test(@"@""\b\w+\b(?!\p{P})""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NegativeLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+\b(?!\p{P})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest25()
{
Test(@"@""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken><</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..57)"" Text=""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*"" />
<Capture Name=""1"" Span=""[10..56)"" Text=""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)"" />
<Capture Name=""2"" Span=""[11..29)"" Text=""((?'Open'<)[^<>]*)"" />
<Capture Name=""3"" Span=""[30..54)"" Text=""((?'Close-Open'>)[^<>]*)"" />
<Capture Name=""4"" Span=""[12..22)"" Text=""(?'Open'<)"" />
<Capture Name=""5"" Span=""[31..47)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[31..47)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Open"" Span=""[12..22)"" Text=""(?'Open'<)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest26()
{
Test(@"@""\b(?!un)\w+\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence>
<Text>
<TextToken>un</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NegativeLookaheadGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""\b(?!un)\w+\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest27()
{
Test(@"@""\b(?ix: d \w+)\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ix</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest28()
{
Test(@"@""(?:\w+)""", @"<Tree>
<CompilationUnit>
<Sequence>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?:\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest29()
{
Test(@"@""(?:\b(?:\w+)\W*)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(?:\b(?:\w+)\W*)+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest30()
{
Test(@"@""(?:\b(?:\w+)\W*)+\.""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(?:\b(?:\w+)\W*)+\."" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest31()
{
Test(@"@""(?'Close-Open'>)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[19..23)"" Text=""Open"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""1"" Span=""[10..26)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[10..26)"" Text=""(?'Close-Open'>)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest32()
{
Test(@"@""[^<>]*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""[^<>]*"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest33()
{
Test(@"@""\b\w+(?=\sis\b)""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<PositiveLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<EqualsToken>=</EqualsToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<Text>
<TextToken>is</TextToken>
</Text>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</PositiveLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""\b\w+(?=\sis\b)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest34()
{
Test(@"@""[a-z-[m]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>m</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[a-z-[m]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest35()
{
Test(@"@""^\D\d{1,5}\D*$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""5"">5</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^\D\d{1,5}\D*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest36()
{
Test(@"@""[^0-9]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""[^0-9]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest37()
{
Test(@"@""(\p{IsGreek}+(\s)?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsGreek</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""(\p{IsGreek}+(\s)?)+"" />
<Capture Name=""1"" Span=""[10..29)"" Text=""(\p{IsGreek}+(\s)?)"" />
<Capture Name=""2"" Span=""[23..27)"" Text=""(\s)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest38()
{
Test(@"@""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsGreek</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Pd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..65)"" Text=""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"" />
<Capture Name=""1"" Span=""[12..31)"" Text=""(\p{IsGreek}+(\s)?)"" />
<Capture Name=""2"" Span=""[25..29)"" Text=""(\s)"" />
<Capture Name=""3"" Span=""[40..64)"" Text=""(\p{IsBasicLatin}+(\s)?)"" />
<Capture Name=""4"" Span=""[58..62)"" Text=""(\s)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest39()
{
Test(@"@""\b.*[.?!;:](\s|\z)""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.?!;:</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>z</TextToken>
</AnchorEscape>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..28)"" Text=""\b.*[.?!;:](\s|\z)"" />
<Capture Name=""1"" Span=""[21..28)"" Text=""(\s|\z)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest40()
{
Test(@"@""^.+""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""^.+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest41()
{
Test(@"@""[^o]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>o</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[^o]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest42()
{
Test(@"@""\bth[^o]\w+\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>th</TextToken>
</Text>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>o</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""\bth[^o]\w+\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest43()
{
Test(@"@""(\P{Sc})+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(\P{Sc})+"" />
<Capture Name=""1"" Span=""[10..18)"" Text=""(\P{Sc})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest44()
{
Test(@"@""[^\p{P}\d]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""[^\p{P}\d]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest45()
{
Test(@"@""\b[A-Z]\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>A</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>Z</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""\b[A-Z]\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest46()
{
Test(@"@""\S+?""", @"<Tree>
<CompilationUnit>
<Sequence>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""\S+?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest47()
{
Test(@"@""y\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>y</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""y\s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest48()
{
Test(@"@""gr[ae]y\s\S+?[\s\p{P}]""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>gr</TextToken>
</Text>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>ae</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<Text>
<TextToken>y</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..32)"" Text=""gr[ae]y\s\S+?[\s\p{P}]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest49()
{
Test(@"@""[\s\p{P}]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[\s\p{P}]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest50()
{
Test(@"@""[\p{P}\d]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[\p{P}\d]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest51()
{
Test(@"@""[^aeiou]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>aeiou</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""[^aeiou]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest52()
{
Test(@"@""(\w)\1""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest53()
{
Test(@"@""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] """, @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lt</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lo</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Nd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Pc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lm</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<Text>
<TextToken> </TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..56)"" Text=""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] "" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest54()
{
Test(@"@""[^a-zA-Z_0-9]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassRange>
<Text>
<TextToken>A</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>Z</TextToken>
</Text>
</CharacterClassRange>
<Text>
<TextToken>_</TextToken>
</Text>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""[^a-zA-Z_0-9]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest55()
{
Test(@"@""\P{Nd}""", @"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Nd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\P{Nd}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest56()
{
Test(@"@""(\(?\d{3}\)?[\s-])?""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(\(?\d{3}\)?[\s-])?"" />
<Capture Name=""1"" Span=""[10..28)"" Text=""(\(?\d{3}\)?[\s-])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest57()
{
Test(@"@""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"" />
<Capture Name=""1"" Span=""[11..29)"" Text=""(\(?\d{3}\)?[\s-])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest58()
{
Test(@"@""[0-9]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""[0-9]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest59()
{
Test(@"@""\p{Nd}""", @"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Nd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\p{Nd}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest60()
{
Test(@"@""\b(\S+)\s?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""\b(\S+)\s?"" />
<Capture Name=""1"" Span=""[12..17)"" Text=""(\S+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest61()
{
Test(@"@""[^ \f\n\r\t\v]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken> </TextToken>
</Text>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>f</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>n</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>t</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>v</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""[^ \f\n\r\t\v]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest62()
{
Test(@"@""[^\f\n\r\t\v\x85\p{Z}]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>f</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>n</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>t</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>v</TextToken>
</SimpleEscape>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>85</TextToken>
</HexEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Z</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..32)"" Text=""[^\f\n\r\t\v\x85\p{Z}]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest63()
{
Test(@"@""(\s|$)""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\s|$)"" />
<Capture Name=""1"" Span=""[10..16)"" Text=""(\s|$)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest64()
{
Test(@"@""\b\w+(e)?s(\s|$)""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>e</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>s</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+(e)?s(\s|$)"" />
<Capture Name=""1"" Span=""[15..18)"" Text=""(e)"" />
<Capture Name=""2"" Span=""[20..26)"" Text=""(\s|$)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest65()
{
Test(@"@""[ \f\n\r\t\v]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken> </TextToken>
</Text>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>f</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>n</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>t</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>v</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""[ \f\n\r\t\v]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest66()
{
Test(@"@""(\W){1,2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(\W){1,2}"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\W)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest67()
{
Test(@"@""(\w+)""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(\w+)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest68()
{
Test(@"@""\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest69()
{
Test(@"@""\b(\w+)(\W){1,2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b(\w+)(\W){1,2}"" />
<Capture Name=""1"" Span=""[12..17)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[17..21)"" Text=""(\W)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest70()
{
Test(@"@""(?>(\w)\1+).\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""(?>(\w)\1+).\b"" />
<Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest71()
{
Test(@"@""(\b(\w+)\W+)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" />
<Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" />
<Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest72()
{
Test(@"@""(\w)\1+.\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest73()
{
Test(@"@""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.,</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"" />
<Capture Name=""1"" Span=""[17..33)"" Text=""(\s?\d+[.,]?\d*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest74()
{
Test(@"@""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>p{Sc</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>}</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""amount"">amount</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.,</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..48)"" Text=""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*"" />
<Capture Name=""1"" Span=""[16..41)"" Text=""(?<amount>\s?\d+[.,]?\d*)"" />
<Capture Name=""amount"" Span=""[16..41)"" Text=""(?<amount>\s?\d+[.,]?\d*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest75()
{
Test(@"@""^(\w+\s?)+$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^(\w+\s?)+$"" />
<Capture Name=""1"" Span=""[11..19)"" Text=""(\w+\s?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest76()
{
Test(@"@""(?ix) d \w+ \s""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ix</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""(?ix) d \w+ \s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest77()
{
Test(@"@""\b(?ix: d \w+)\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ix</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest78()
{
Test(@"@""\bthe\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>the</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""\bthe\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest79()
{
Test(@"@""\b(?i:t)he\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>i</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<Text>
<TextToken>t</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<Text>
<TextToken>he</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""\b(?i:t)he\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest80()
{
Test(@"@""^(\w+)\s(\d+)$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^(\w+)\s(\d+)$"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest81()
{
Test(@"@""^(\w+)\s(\d+)\r*$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""^(\w+)\s(\d+)\r*$"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" />
</Captures>
</Tree>", RegexOptions.Multiline);
}
[Fact]
public void ReferenceTest82()
{
Test(@"@""(?m)^(\w+)\s(\d+)\r*$""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>m</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..31)"" Text=""(?m)^(\w+)\s(\d+)\r*$"" />
<Capture Name=""1"" Span=""[15..20)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[22..27)"" Text=""(\d+)"" />
</Captures>
</Tree>", RegexOptions.Multiline);
}
[Fact]
public void ReferenceTest83()
{
Test(@"@""(?s)^.+""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>s</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?s)^.+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest84()
{
Test(@"@""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<NumberToken value=""1"">1</NumberToken>
<CloseParenToken>)</CloseParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""7"">7</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..52)"" Text=""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"" />
<Capture Name=""1"" Span=""[12..20)"" Text=""(\d{2}-)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest85()
{
Test(@"@""\b\(?((\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..37)"" Text=""\b\(?((\w+),?\s?)+[\.!?]\)?"" />
<Capture Name=""1"" Span=""[15..27)"" Text=""((\w+),?\s?)"" />
<Capture Name=""2"" Span=""[16..21)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest86()
{
Test(@"@""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>n</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest87()
{
Test(@"@""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>n</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest88()
{
Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?>\w+),?\s?)+[\.!?]\)?"" />
<Capture Name=""1"" Span=""[15..29)"" Text=""((?>\w+),?\s?)"" />
</Captures>
</Tree>", RegexOptions.IgnorePatternWhitespace);
}
[Fact]
public void ReferenceTest89()
{
Test(@"@""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>x</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia># Matches an entire sentence.</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..81)"" Text=""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence."" />
<Capture Name=""1"" Span=""[21..38)"" Text=""( (?>\w+) ,?\s? )"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest90()
{
Test(@"@""\bb\w+\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>b</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\bb\w+\s"" />
</Captures>
</Tree>", RegexOptions.RightToLeft);
}
[Fact]
public void ReferenceTest91()
{
Test(@"@""(?<=\d{1,2}\s)\w+,?\s\d{4}""", @"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<EqualsToken>=</EqualsToken>
<Sequence>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</PositiveLookbehindGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..36)"" Text=""(?<=\d{1,2}\s)\w+,?\s\d{4}"" />
</Captures>
</Tree>", RegexOptions.RightToLeft);
}
[Fact]
public void ReferenceTest92()
{
Test(@"@""\b(\w+\s*)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""\b(\w+\s*)+"" />
<Capture Name=""1"" Span=""[12..20)"" Text=""(\w+\s*)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void ReferenceTest93()
{
Test(@"@""((a+)(\1) ?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<Text>
<TextToken>a</TextToken>
</Text>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""((a+)(\1) ?)+"" />
<Capture Name=""1"" Span=""[10..22)"" Text=""((a+)(\1) ?)"" />
<Capture Name=""2"" Span=""[11..15)"" Text=""(a+)"" />
<Capture Name=""3"" Span=""[15..19)"" Text=""(\1)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void ReferenceTest94()
{
Test(@"@""\b(D\w+)\s(d\w+)\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..28)"" Text=""\b(D\w+)\s(d\w+)\b"" />
<Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" />
<Capture Name=""2"" Span=""[20..26)"" Text=""(d\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest95()
{
Test(@"@""\b(D\w+)(?ixn) \s (d\w+) \b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ixn</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..37)"" Text=""\b(D\w+)(?ixn) \s (d\w+) \b"" />
<Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest96()
{
Test(@"@""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?# case-sensitive comparison)</CommentTrivia>
</Trivia>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?#case-insensitive comparison)</CommentTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..89)"" Text=""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b"" />
<Capture Name=""1"" Span=""[12..48)"" Text=""((?# case-sensitive comparison)D\w+)"" />
<Capture Name=""2"" Span=""[50..87)"" Text=""((?#case-insensitive comparison)d\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest97()
{
Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?>\w+),?\s?)+[\.!?]\)?"" />
<Capture Name=""1"" Span=""[15..29)"" Text=""((?>\w+),?\s?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest98()
{
Test(@"@""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""n2"">n2</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<CaptureNameToken value=""n2"">n2</CaptureNameToken>
<CloseParenToken>)</CloseParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""7"">7</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..58)"" Text=""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"" />
<Capture Name=""1"" Span=""[12..25)"" Text=""(?<n2>\d{2}-)"" />
<Capture Name=""n2"" Span=""[12..25)"" Text=""(?<n2>\d{2}-)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest99()
{
Test(@"@""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""7"">7</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..45)"" Text=""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"" />
<Capture Name=""1"" Span=""[12..43)"" Text=""(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest100()
{
Test(@"@""\bgr(a|e)y\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>gr</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>e</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>y</TextToken>
</Text>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""\bgr(a|e)y\b"" />
<Capture Name=""1"" Span=""[14..19)"" Text=""(a|e)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest101()
{
Test(@"@""(?>(\w)\1+).\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""(?>(\w)\1+).\b"" />
<Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest102()
{
Test(@"@""(\b(\w+)\W+)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" />
<Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" />
<Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest103()
{
Test(@"@""\b91*9*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>9</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>1</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>9</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""\b91*9*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest104()
{
Test(@"@""\ban+\w*?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>a</TextToken>
</Text>
<OneOrMoreQuantifier>
<Text>
<TextToken>n</TextToken>
</Text>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""\ban+\w*?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest105()
{
Test(@"@""\ban?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>a</TextToken>
</Text>
<ZeroOrOneQuantifier>
<Text>
<TextToken>n</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\ban?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest106()
{
Test(@"@""\b\d+\,\d{3}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>,</TextToken>
</SimpleEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""\b\d+\,\d{3}\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest107()
{
Test(@"@""\b\d{2,}\b\D+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OpenRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""\b\d{2,}\b\D+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest108()
{
Test(@"@""(00\s){2,4}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>00</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""(00\s){2,4}"" />
<Capture Name=""1"" Span=""[10..16)"" Text=""(00\s)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest109()
{
Test(@"@""\b\w*?oo\w*?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>oo</TextToken>
</Text>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""\b\w*?oo\w*?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest110()
{
Test(@"@""\b\w+?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\b\w+?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest111()
{
Test(@"@""^\s*(System.)??Console.Write(Line)??\(??""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>System</TextToken>
</Text>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>Console</TextToken>
</Text>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<Text>
<TextToken>Write</TextToken>
</Text>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>Line</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..50)"" Text=""^\s*(System.)??Console.Write(Line)??\(??"" />
<Capture Name=""1"" Span=""[14..23)"" Text=""(System.)"" />
<Capture Name=""2"" Span=""[38..44)"" Text=""(Line)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest112()
{
Test(@"@""(System.)??""", @"<Tree>
<CompilationUnit>
<Sequence>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>System</TextToken>
</Text>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""(System.)??"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""(System.)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest113()
{
Test(@"@""\b(\w{3,}?\.){2}?\w{3,}?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<ExactNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<LazyQuantifier>
<OpenRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<LazyQuantifier>
<OpenRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..36)"" Text=""\b(\w{3,}?\.){2}?\w{3,}?\b"" />
<Capture Name=""1"" Span=""[12..23)"" Text=""(\w{3,}?\.)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest114()
{
Test(@"@""\b[A-Z](\w*?\s*?){1,10}[.!?]""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>A</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>Z</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""10"">10</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""\b[A-Z](\w*?\s*?){1,10}[.!?]"" />
<Capture Name=""1"" Span=""[17..27)"" Text=""(\w*?\s*?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest115()
{
Test(@"@""b.*([0-9]{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>b</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""b.*([0-9]{4})\b"" />
<Capture Name=""1"" Span=""[13..23)"" Text=""([0-9]{4})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest116()
{
Test(@"@""\b.*?([0-9]{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""\b.*?([0-9]{4})\b"" />
<Capture Name=""1"" Span=""[15..25)"" Text=""([0-9]{4})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest117()
{
Test(@"@""(a?)*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<Text>
<TextToken>a</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(a?)*"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(a?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest118()
{
Test(@"@""(a\1|(?(1)\1)){0,2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<NumberToken value=""1"">1</NumberToken>
<CloseParenToken>)</CloseParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""0"">0</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(a\1|(?(1)\1)){0,2}"" />
<Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest119()
{
Test(@"@""(a\1|(?(1)\1)){2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ExactNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<NumberToken value=""1"">1</NumberToken>
<CloseParenToken>)</CloseParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(a\1|(?(1)\1)){2}"" />
<Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest120()
{
Test(@"@""(\w)\1""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest121()
{
Test(@"@""(?<char>\w)\k<char>""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""char"">char</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""char"">char</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(?<char>\w)\k<char>"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<char>\w)"" />
<Capture Name=""char"" Span=""[10..21)"" Text=""(?<char>\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest122()
{
Test(@"@""(?<2>\w)\k<2>""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""2"">2</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""2"">2</NumberToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""(?<2>\w)\k<2>"" />
<Capture Name=""2"" Span=""[10..18)"" Text=""(?<2>\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest123()
{
Test(@"@""(?<1>a)(?<1>\1b)*""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<Text>
<TextToken>b</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(?<1>a)(?<1>\1b)*"" />
<Capture Name=""1"" Span=""[10..17)"" Text=""(?<1>a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest124()
{
Test(@"@""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..44)"" Text=""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b"" />
<Capture Name=""1"" Span=""[12..23)"" Text=""(\p{Lu}{2})"" />
<Capture Name=""2"" Span=""[23..30)"" Text=""(\d{2})"" />
<Capture Name=""3"" Span=""[31..42)"" Text=""(\p{Lu}{2})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest125()
{
Test(@"@""\bgr[ae]y\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>gr</TextToken>
</Text>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>ae</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<Text>
<TextToken>y</TextToken>
</Text>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""\bgr[ae]y\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest126()
{
Test(@"@""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?# case sensitive comparison)</CommentTrivia>
</Trivia>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ixn</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?#case insensitive comparison)</CommentTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..95)"" Text=""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b"" />
<Capture Name=""1"" Span=""[12..48)"" Text=""((?# case sensitive comparison)D\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest127()
{
Test(@"@""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>{</TextToken>
</SimpleEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>,</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>:</TextToken>
</SimpleEscape>
<LazyQuantifier>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>}</TextToken>
</SimpleEscape>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>x</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
</Sequence>
<EndOfFile>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia># Looks for a composite format item.</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..80)"" Text=""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."" />
<Capture Name=""1"" Span=""[15..23)"" Text=""(,-*\d+)"" />
<Capture Name=""2"" Span=""[24..36)"" Text=""(\:\w{1,4}?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Text.RegularExpressions;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions
{
// All these tests came from the example at:
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference
public partial class CSharpRegexParserTests
{
[Fact]
public void ReferenceTest0()
{
Test(@"@""[aeiou]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>aeiou</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""[aeiou]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest1()
{
Test(@"@""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""nextWord"">nextWord</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..68)"" Text=""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)"" />
<Capture Name=""1"" Span=""[10..31)"" Text=""(?<duplicateWord>\w+)"" />
<Capture Name=""2"" Span=""[52..68)"" Text=""(?<nextWord>\w+)"" />
<Capture Name=""duplicateWord"" Span=""[10..31)"" Text=""(?<duplicateWord>\w+)"" />
<Capture Name=""nextWord"" Span=""[52..68)"" Text=""(?<nextWord>\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest2()
{
Test(@"@""((?<One>abc)\d+)?(?<Two>xyz)(.*)""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""One"">One</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>abc</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""Two"">Two</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>xyz</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""((?<One>abc)\d+)?(?<Two>xyz)(.*)"" />
<Capture Name=""1"" Span=""[10..26)"" Text=""((?<One>abc)\d+)"" />
<Capture Name=""2"" Span=""[38..42)"" Text=""(.*)"" />
<Capture Name=""3"" Span=""[11..22)"" Text=""(?<One>abc)"" />
<Capture Name=""4"" Span=""[27..38)"" Text=""(?<Two>xyz)"" />
<Capture Name=""One"" Span=""[11..22)"" Text=""(?<One>abc)"" />
<Capture Name=""Two"" Span=""[27..38)"" Text=""(?<Two>xyz)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest3()
{
Test(@"@""(\w+)\s(\1)""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""(\w+)\s(\1)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[17..21)"" Text=""(\1)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest4()
{
Test(@"@""\Bqu\w+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>B</TextToken>
</AnchorEscape>
<Text>
<TextToken>qu</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\Bqu\w+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest5()
{
Test(@"@""\bare\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>are</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""\bare\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest6()
{
Test(@"@""\G(\w+\s?\w*),?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>G</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""\G(\w+\s?\w*),?"" />
<Capture Name=""1"" Span=""[12..23)"" Text=""(\w+\s?\w*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest7()
{
Test(@"@""\D+(?<digit>\d+)\D+(?<digit>\d+)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""digit"">digit</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""digit"">digit</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""\D+(?<digit>\d+)\D+(?<digit>\d+)?"" />
<Capture Name=""1"" Span=""[13..26)"" Text=""(?<digit>\d+)"" />
<Capture Name=""digit"" Span=""[13..26)"" Text=""(?<digit>\d+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest8()
{
Test(@"@""(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>-</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>&#124;present</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..46)"" Text=""(\s\d{4}(-(\d{4}&#124;present))?,?)+"" />
<Capture Name=""1"" Span=""[10..45)"" Text=""(\s\d{4}(-(\d{4}&#124;present))?,?)"" />
<Capture Name=""2"" Span=""[18..41)"" Text=""(-(\d{4}&#124;present))"" />
<Capture Name=""3"" Span=""[20..40)"" Text=""(\d{4}&#124;present)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest9()
{
Test(@"@""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OpenRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>,</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>,</TextToken>
</Text>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>-</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>present</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..72)"" Text=""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"" />
<Capture Name=""1"" Span=""[11..27)"" Text=""((\w+(\s?)){2,})"" />
<Capture Name=""2"" Span=""[12..22)"" Text=""(\w+(\s?))"" />
<Capture Name=""3"" Span=""[16..21)"" Text=""(\s?)"" />
<Capture Name=""4"" Span=""[30..40)"" Text=""(\w+\s\w+)"" />
<Capture Name=""5"" Span=""[41..71)"" Text=""(\s\d{4}(-(\d{4}|present))?,?)"" />
<Capture Name=""6"" Span=""[49..67)"" Text=""(-(\d{4}|present))"" />
<Capture Name=""7"" Span=""[51..66)"" Text=""(\d{4}|present)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest10()
{
Test(@"@""^[0-9-[2468]]+$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>2468</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""^[0-9-[2468]]+$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest11()
{
Test(@"@""[a-z-[0-9]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[0-9]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest12()
{
Test(@"@""[\p{IsBasicLatin}-[\x00-\x7F]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>00</TextToken>
</HexEscape>
<MinusToken>-</MinusToken>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>7F</TextToken>
</HexEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""[\p{IsBasicLatin}-[\x00-\x7F]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest13()
{
Test(@"@""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>0000</TextToken>
</UnicodeEscape>
<MinusToken>-</MinusToken>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>FFFF</TextToken>
</UnicodeEscape>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsGreek</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>85</TextToken>
</HexEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..50)"" Text=""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest14()
{
Test(@"@""[a-z-[d-w-[m-o]]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>d</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>w</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>m</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>o</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""[a-z-[d-w-[m-o]]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest15()
{
Test(@"@""((\w+(\s?)){2,}""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OpenRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}}</CloseBraceToken>
</OpenRangeNumericQuantifier>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[25..25)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" />
<Capture Name=""1"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" />
<Capture Name=""2"" Span=""[11..21)"" Text=""(\w+(\s?))"" />
<Capture Name=""3"" Span=""[15..20)"" Text=""(\s?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest16()
{
Test(@"@""[a-z-[djp]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>djp</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[djp]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest17()
{
Test(@"@""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken><</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<CloseParenToken>)</CloseParenToken>
<Sequence>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</NegativeLookaheadGrouping>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..78)"" Text=""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$"" />
<Capture Name=""1"" Span=""[17..63)"" Text=""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)"" />
<Capture Name=""2"" Span=""[18..36)"" Text=""((?'Open'<)[^<>]*)"" />
<Capture Name=""3"" Span=""[37..61)"" Text=""((?'Close-Open'>)[^<>]*)"" />
<Capture Name=""4"" Span=""[19..29)"" Text=""(?'Open'<)"" />
<Capture Name=""5"" Span=""[38..54)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[38..54)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Open"" Span=""[19..29)"" Text=""(?'Open'<)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest18()
{
Test(@"@""((?'Close-Open'>)[^<>]*)+""", $@"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[20..24)"" Text=""Open"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..35)"" Text=""((?'Close-Open'>)[^<>]*)+"" />
<Capture Name=""1"" Span=""[10..34)"" Text=""((?'Close-Open'>)[^<>]*)"" />
<Capture Name=""2"" Span=""[11..27)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[11..27)"" Text=""(?'Close-Open'>)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest19()
{
Test(@"@""(\w)\1+.\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest20()
{
Test(@"@""\d{4}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\d{4}\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest21()
{
Test(@"@""\d{1,2},""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\d{1,2},"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest22()
{
Test(@"@""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegativeLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<ExclamationToken>!</ExclamationToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>Saturday</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>Sunday</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken> </TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NegativeLookbehindGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<Text>
<TextToken>, </TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..55)"" Text=""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"" />
<Capture Name=""1"" Span=""[14..31)"" Text=""(Saturday|Sunday)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest23()
{
Test(@"@""(?<=\b20)\d{2}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<EqualsToken>=</EqualsToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>20</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</PositiveLookbehindGrouping>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(?<=\b20)\d{2}\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest24()
{
Test(@"@""\b\w+\b(?!\p{P})""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NegativeLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+\b(?!\p{P})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest25()
{
Test(@"@""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken><</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..57)"" Text=""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*"" />
<Capture Name=""1"" Span=""[10..56)"" Text=""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)"" />
<Capture Name=""2"" Span=""[11..29)"" Text=""((?'Open'<)[^<>]*)"" />
<Capture Name=""3"" Span=""[30..54)"" Text=""((?'Close-Open'>)[^<>]*)"" />
<Capture Name=""4"" Span=""[12..22)"" Text=""(?'Open'<)"" />
<Capture Name=""5"" Span=""[31..47)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[31..47)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Open"" Span=""[12..22)"" Text=""(?'Open'<)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest26()
{
Test(@"@""\b(?!un)\w+\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence>
<Text>
<TextToken>un</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NegativeLookaheadGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""\b(?!un)\w+\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest27()
{
Test(@"@""\b(?ix: d \w+)\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ix</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest28()
{
Test(@"@""(?:\w+)""", @"<Tree>
<CompilationUnit>
<Sequence>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?:\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest29()
{
Test(@"@""(?:\b(?:\w+)\W*)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(?:\b(?:\w+)\W*)+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest30()
{
Test(@"@""(?:\b(?:\w+)\W*)+\.""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NonCapturingGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(?:\b(?:\w+)\W*)+\."" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest31()
{
Test(@"@""(?'Close-Open'>)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""Close"">Close</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""Open"">Open</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[19..23)"" Text=""Open"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""1"" Span=""[10..26)"" Text=""(?'Close-Open'>)"" />
<Capture Name=""Close"" Span=""[10..26)"" Text=""(?'Close-Open'>)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void ReferenceTest32()
{
Test(@"@""[^<>]*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""[^<>]*"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest33()
{
Test(@"@""\b\w+(?=\sis\b)""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<PositiveLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<EqualsToken>=</EqualsToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<Text>
<TextToken>is</TextToken>
</Text>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</PositiveLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""\b\w+(?=\sis\b)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest34()
{
Test(@"@""[a-z-[m]]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>m</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[a-z-[m]]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest35()
{
Test(@"@""^\D\d{1,5}\D*$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""5"">5</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^\D\d{1,5}\D*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest36()
{
Test(@"@""[^0-9]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""[^0-9]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest37()
{
Test(@"@""(\p{IsGreek}+(\s)?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsGreek</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""(\p{IsGreek}+(\s)?)+"" />
<Capture Name=""1"" Span=""[10..29)"" Text=""(\p{IsGreek}+(\s)?)"" />
<Capture Name=""2"" Span=""[23..27)"" Text=""(\s)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest38()
{
Test(@"@""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsGreek</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Pd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..65)"" Text=""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"" />
<Capture Name=""1"" Span=""[12..31)"" Text=""(\p{IsGreek}+(\s)?)"" />
<Capture Name=""2"" Span=""[25..29)"" Text=""(\s)"" />
<Capture Name=""3"" Span=""[40..64)"" Text=""(\p{IsBasicLatin}+(\s)?)"" />
<Capture Name=""4"" Span=""[58..62)"" Text=""(\s)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest39()
{
Test(@"@""\b.*[.?!;:](\s|\z)""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.?!;:</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>z</TextToken>
</AnchorEscape>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..28)"" Text=""\b.*[.?!;:](\s|\z)"" />
<Capture Name=""1"" Span=""[21..28)"" Text=""(\s|\z)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest40()
{
Test(@"@""^.+""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""^.+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest41()
{
Test(@"@""[^o]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>o</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[^o]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest42()
{
Test(@"@""\bth[^o]\w+\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>th</TextToken>
</Text>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>o</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""\bth[^o]\w+\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest43()
{
Test(@"@""(\P{Sc})+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(\P{Sc})+"" />
<Capture Name=""1"" Span=""[10..18)"" Text=""(\P{Sc})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest44()
{
Test(@"@""[^\p{P}\d]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""[^\p{P}\d]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest45()
{
Test(@"@""\b[A-Z]\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>A</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>Z</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""\b[A-Z]\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest46()
{
Test(@"@""\S+?""", @"<Tree>
<CompilationUnit>
<Sequence>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""\S+?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest47()
{
Test(@"@""y\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>y</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""y\s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest48()
{
Test(@"@""gr[ae]y\s\S+?[\s\p{P}]""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>gr</TextToken>
</Text>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>ae</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<Text>
<TextToken>y</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..32)"" Text=""gr[ae]y\s\S+?[\s\p{P}]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest49()
{
Test(@"@""[\s\p{P}]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[\s\p{P}]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest50()
{
Test(@"@""[\p{P}\d]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>P</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[\p{P}\d]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest51()
{
Test(@"@""[^aeiou]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>aeiou</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""[^aeiou]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest52()
{
Test(@"@""(\w)\1""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest53()
{
Test(@"@""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] """, @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lt</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lo</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Nd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Pc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lm</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
<Text>
<TextToken> </TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..56)"" Text=""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] "" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest54()
{
Test(@"@""[^a-zA-Z_0-9]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>z</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassRange>
<Text>
<TextToken>A</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>Z</TextToken>
</Text>
</CharacterClassRange>
<Text>
<TextToken>_</TextToken>
</Text>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""[^a-zA-Z_0-9]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest55()
{
Test(@"@""\P{Nd}""", @"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Nd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\P{Nd}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest56()
{
Test(@"@""(\(?\d{3}\)?[\s-])?""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(\(?\d{3}\)?[\s-])?"" />
<Capture Name=""1"" Span=""[10..28)"" Text=""(\(?\d{3}\)?[\s-])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest57()
{
Test(@"@""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"" />
<Capture Name=""1"" Span=""[11..29)"" Text=""(\(?\d{3}\)?[\s-])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest58()
{
Test(@"@""[0-9]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""[0-9]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest59()
{
Test(@"@""\p{Nd}""", @"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Nd</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\p{Nd}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest60()
{
Test(@"@""\b(\S+)\s?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""\b(\S+)\s?"" />
<Capture Name=""1"" Span=""[12..17)"" Text=""(\S+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest61()
{
Test(@"@""[^ \f\n\r\t\v]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken> </TextToken>
</Text>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>f</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>n</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>t</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>v</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""[^ \f\n\r\t\v]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest62()
{
Test(@"@""[^\f\n\r\t\v\x85\p{Z}]""", @"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>f</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>n</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>t</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>v</TextToken>
</SimpleEscape>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>85</TextToken>
</HexEscape>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Z</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..32)"" Text=""[^\f\n\r\t\v\x85\p{Z}]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest63()
{
Test(@"@""(\s|$)""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\s|$)"" />
<Capture Name=""1"" Span=""[10..16)"" Text=""(\s|$)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest64()
{
Test(@"@""\b\w+(e)?s(\s|$)""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>e</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>s</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+(e)?s(\s|$)"" />
<Capture Name=""1"" Span=""[15..18)"" Text=""(e)"" />
<Capture Name=""2"" Span=""[20..26)"" Text=""(\s|$)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest65()
{
Test(@"@""[ \f\n\r\t\v]""", @"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken> </TextToken>
</Text>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>f</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>n</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>t</TextToken>
</SimpleEscape>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>v</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""[ \f\n\r\t\v]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest66()
{
Test(@"@""(\W){1,2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(\W){1,2}"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\W)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest67()
{
Test(@"@""(\w+)""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(\w+)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest68()
{
Test(@"@""\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest69()
{
Test(@"@""\b(\w+)(\W){1,2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b(\w+)(\W){1,2}"" />
<Capture Name=""1"" Span=""[12..17)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[17..21)"" Text=""(\W)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest70()
{
Test(@"@""(?>(\w)\1+).\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""(?>(\w)\1+).\b"" />
<Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest71()
{
Test(@"@""(\b(\w+)\W+)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" />
<Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" />
<Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest72()
{
Test(@"@""(\w)\1+.\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest73()
{
Test(@"@""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.,</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"" />
<Capture Name=""1"" Span=""[17..33)"" Text=""(\s?\d+[.,]?\d*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest74()
{
Test(@"@""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>p{Sc</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>}</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""amount"">amount</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.,</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Sc</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..48)"" Text=""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*"" />
<Capture Name=""1"" Span=""[16..41)"" Text=""(?<amount>\s?\d+[.,]?\d*)"" />
<Capture Name=""amount"" Span=""[16..41)"" Text=""(?<amount>\s?\d+[.,]?\d*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest75()
{
Test(@"@""^(\w+\s?)+$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^(\w+\s?)+$"" />
<Capture Name=""1"" Span=""[11..19)"" Text=""(\w+\s?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest76()
{
Test(@"@""(?ix) d \w+ \s""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ix</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""(?ix) d \w+ \s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest77()
{
Test(@"@""\b(?ix: d \w+)\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ix</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest78()
{
Test(@"@""\bthe\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>the</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""\bthe\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest79()
{
Test(@"@""\b(?i:t)he\w*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>i</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<Text>
<TextToken>t</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<Text>
<TextToken>he</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""\b(?i:t)he\w*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest80()
{
Test(@"@""^(\w+)\s(\d+)$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^(\w+)\s(\d+)$"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest81()
{
Test(@"@""^(\w+)\s(\d+)\r*$""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""^(\w+)\s(\d+)\r*$"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" />
</Captures>
</Tree>", RegexOptions.Multiline);
}
[Fact]
public void ReferenceTest82()
{
Test(@"@""(?m)^(\w+)\s(\d+)\r*$""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>m</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>r</TextToken>
</SimpleEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..31)"" Text=""(?m)^(\w+)\s(\d+)\r*$"" />
<Capture Name=""1"" Span=""[15..20)"" Text=""(\w+)"" />
<Capture Name=""2"" Span=""[22..27)"" Text=""(\d+)"" />
</Captures>
</Tree>", RegexOptions.Multiline);
}
[Fact]
public void ReferenceTest83()
{
Test(@"@""(?s)^.+""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>s</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?s)^.+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest84()
{
Test(@"@""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<NumberToken value=""1"">1</NumberToken>
<CloseParenToken>)</CloseParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""7"">7</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..52)"" Text=""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"" />
<Capture Name=""1"" Span=""[12..20)"" Text=""(\d{2}-)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest85()
{
Test(@"@""\b\(?((\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..37)"" Text=""\b\(?((\w+),?\s?)+[\.!?]\)?"" />
<Capture Name=""1"" Span=""[15..27)"" Text=""((\w+),?\s?)"" />
<Capture Name=""2"" Span=""[16..21)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest86()
{
Test(@"@""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>n</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest87()
{
Test(@"@""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<NestedOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>n</OptionsToken>
<ColonToken>:</ColonToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</NestedOptionsGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest88()
{
Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?>\w+),?\s?)+[\.!?]\)?"" />
<Capture Name=""1"" Span=""[15..29)"" Text=""((?>\w+),?\s?)"" />
</Captures>
</Tree>", RegexOptions.IgnorePatternWhitespace);
}
[Fact]
public void ReferenceTest89()
{
Test(@"@""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>x</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia># Matches an entire sentence.</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..81)"" Text=""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence."" />
<Capture Name=""1"" Span=""[21..38)"" Text=""( (?>\w+) ,?\s? )"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest90()
{
Test(@"@""\bb\w+\s""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>b</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\bb\w+\s"" />
</Captures>
</Tree>", RegexOptions.RightToLeft);
}
[Fact]
public void ReferenceTest91()
{
Test(@"@""(?<=\d{1,2}\s)\w+,?\s\d{4}""", @"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<EqualsToken>=</EqualsToken>
<Sequence>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</PositiveLookbehindGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..36)"" Text=""(?<=\d{1,2}\s)\w+,?\s\d{4}"" />
</Captures>
</Tree>", RegexOptions.RightToLeft);
}
[Fact]
public void ReferenceTest92()
{
Test(@"@""\b(\w+\s*)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""\b(\w+\s*)+"" />
<Capture Name=""1"" Span=""[12..20)"" Text=""(\w+\s*)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void ReferenceTest93()
{
Test(@"@""((a+)(\1) ?)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<Text>
<TextToken>a</TextToken>
</Text>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""((a+)(\1) ?)+"" />
<Capture Name=""1"" Span=""[10..22)"" Text=""((a+)(\1) ?)"" />
<Capture Name=""2"" Span=""[11..15)"" Text=""(a+)"" />
<Capture Name=""3"" Span=""[15..19)"" Text=""(\1)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void ReferenceTest94()
{
Test(@"@""\b(D\w+)\s(d\w+)\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..28)"" Text=""\b(D\w+)\s(d\w+)\b"" />
<Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" />
<Capture Name=""2"" Span=""[20..26)"" Text=""(d\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest95()
{
Test(@"@""\b(D\w+)(?ixn) \s (d\w+) \b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ixn</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..37)"" Text=""\b(D\w+)(?ixn) \s (d\w+) \b"" />
<Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest96()
{
Test(@"@""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?# case-sensitive comparison)</CommentTrivia>
</Trivia>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?#case-insensitive comparison)</CommentTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..89)"" Text=""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b"" />
<Capture Name=""1"" Span=""[12..48)"" Text=""((?# case-sensitive comparison)D\w+)"" />
<Capture Name=""2"" Span=""[50..87)"" Text=""((?#case-insensitive comparison)d\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest97()
{
Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<ZeroOrOneQuantifier>
<Text>
<TextToken>,</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<ZeroOrOneQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
<Text>
<TextToken>!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>)</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?>\w+),?\s?)+[\.!?]\)?"" />
<Capture Name=""1"" Span=""[15..29)"" Text=""((?>\w+),?\s?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest98()
{
Test(@"@""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<ZeroOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""n2"">n2</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<CaptureNameToken value=""n2"">n2</CaptureNameToken>
<CloseParenToken>)</CloseParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""7"">7</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..58)"" Text=""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"" />
<Capture Name=""1"" Span=""[12..25)"" Text=""(?<n2>\d{2}-)"" />
<Capture Name=""n2"" Span=""[12..25)"" Text=""(?<n2>\d{2}-)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest99()
{
Test(@"@""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""7"">7</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..45)"" Text=""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"" />
<Capture Name=""1"" Span=""[12..43)"" Text=""(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest100()
{
Test(@"@""\bgr(a|e)y\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>gr</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>e</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>y</TextToken>
</Text>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""\bgr(a|e)y\b"" />
<Capture Name=""1"" Span=""[14..19)"" Text=""(a|e)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest101()
{
Test(@"@""(?>(\w)\1+).\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</AtomicGrouping>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""(?>(\w)\1+).\b"" />
<Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest102()
{
Test(@"@""(\b(\w+)\W+)+""", @"<Tree>
<CompilationUnit>
<Sequence>
<OneOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" />
<Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" />
<Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest103()
{
Test(@"@""\b91*9*\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>9</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>1</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>9</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""\b91*9*\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest104()
{
Test(@"@""\ban+\w*?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>a</TextToken>
</Text>
<OneOrMoreQuantifier>
<Text>
<TextToken>n</TextToken>
</Text>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""\ban+\w*?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest105()
{
Test(@"@""\ban?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>a</TextToken>
</Text>
<ZeroOrOneQuantifier>
<Text>
<TextToken>n</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\ban?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest106()
{
Test(@"@""\b\d+\,\d{3}\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>,</TextToken>
</SimpleEscape>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""\b\d+\,\d{3}\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest107()
{
Test(@"@""\b\d{2,}\b\D+""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OpenRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""\b\d{2,}\b\D+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest108()
{
Test(@"@""(00\s){2,4}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>00</TextToken>
</Text>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""(00\s){2,4}"" />
<Capture Name=""1"" Span=""[10..16)"" Text=""(00\s)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest109()
{
Test(@"@""\b\w*?oo\w*?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>oo</TextToken>
</Text>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""\b\w*?oo\w*?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest110()
{
Test(@"@""\b\w+?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\b\w+?\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest111()
{
Test(@"@""^\s*(System.)??Console.Write(Line)??\(??""", @"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>System</TextToken>
</Text>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>Console</TextToken>
</Text>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<Text>
<TextToken>Write</TextToken>
</Text>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>Line</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>(</TextToken>
</SimpleEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..50)"" Text=""^\s*(System.)??Console.Write(Line)??\(??"" />
<Capture Name=""1"" Span=""[14..23)"" Text=""(System.)"" />
<Capture Name=""2"" Span=""[38..44)"" Text=""(Line)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest112()
{
Test(@"@""(System.)??""", @"<Tree>
<CompilationUnit>
<Sequence>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>System</TextToken>
</Text>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""(System.)??"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""(System.)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest113()
{
Test(@"@""\b(\w{3,}?\.){2}?\w{3,}?\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<ExactNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<LazyQuantifier>
<OpenRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>.</TextToken>
</SimpleEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<LazyQuantifier>
<OpenRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""3"">3</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..36)"" Text=""\b(\w{3,}?\.){2}?\w{3,}?\b"" />
<Capture Name=""1"" Span=""[12..23)"" Text=""(\w{3,}?\.)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest114()
{
Test(@"@""\b[A-Z](\w*?\s*?){1,10}[.!?]""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>A</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>Z</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""10"">10</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>.!?</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""\b[A-Z](\w*?\s*?){1,10}[.!?]"" />
<Capture Name=""1"" Span=""[17..27)"" Text=""(\w*?\s*?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest115()
{
Test(@"@""b.*([0-9]{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>b</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""b.*([0-9]{4})\b"" />
<Capture Name=""1"" Span=""[13..23)"" Text=""([0-9]{4})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest116()
{
Test(@"@""\b.*?([0-9]{4})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<Wildcard>
<DotToken>.</DotToken>
</Wildcard>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>0</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>9</TextToken>
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""\b.*?([0-9]{4})\b"" />
<Capture Name=""1"" Span=""[15..25)"" Text=""([0-9]{4})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest117()
{
Test(@"@""(a?)*""", @"<Tree>
<CompilationUnit>
<Sequence>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<Text>
<TextToken>a</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(a?)*"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(a?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest118()
{
Test(@"@""(a\1|(?(1)\1)){0,2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ClosedRangeNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<NumberToken value=""1"">1</NumberToken>
<CloseParenToken>)</CloseParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""0"">0</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(a\1|(?(1)\1)){0,2}"" />
<Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest119()
{
Test(@"@""(a\1|(?(1)\1)){2}""", @"<Tree>
<CompilationUnit>
<Sequence>
<ExactNumericQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<ConditionalCaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OpenParenToken>(</OpenParenToken>
<NumberToken value=""1"">1</NumberToken>
<CloseParenToken>)</CloseParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalCaptureGrouping>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(a\1|(?(1)\1)){2}"" />
<Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest120()
{
Test(@"@""(\w)\1""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest121()
{
Test(@"@""(?<char>\w)\k<char>""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""char"">char</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""char"">char</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""(?<char>\w)\k<char>"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<char>\w)"" />
<Capture Name=""char"" Span=""[10..21)"" Text=""(?<char>\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest122()
{
Test(@"@""(?<2>\w)\k<2>""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""2"">2</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""2"">2</NumberToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""(?<2>\w)\k<2>"" />
<Capture Name=""2"" Span=""[10..18)"" Text=""(?<2>\w)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest123()
{
Test(@"@""(?<1>a)(?<1>\1b)*""", @"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
<Text>
<TextToken>b</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(?<1>a)(?<1>\1b)*"" />
<Capture Name=""1"" Span=""[10..17)"" Text=""(?<1>a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest124()
{
Test(@"@""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ExactNumericQuantifier>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}</CloseBraceToken>
</CategoryEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""2"">2</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ExactNumericQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..44)"" Text=""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b"" />
<Capture Name=""1"" Span=""[12..23)"" Text=""(\p{Lu}{2})"" />
<Capture Name=""2"" Span=""[23..30)"" Text=""(\d{2})"" />
<Capture Name=""3"" Span=""[31..42)"" Text=""(\p{Lu}{2})"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest125()
{
Test(@"@""\bgr[ae]y\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<Text>
<TextToken>gr</TextToken>
</Text>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>ae</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<Text>
<TextToken>y</TextToken>
</Text>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""\bgr[ae]y\b"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest126()
{
Test(@"@""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b""", @"<Tree>
<CompilationUnit>
<Sequence>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?# case sensitive comparison)</CommentTrivia>
</Trivia>D</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>ixn</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?#case insensitive comparison)</CommentTrivia>
</Trivia>d</TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AnchorEscape>
<BackslashToken>\</BackslashToken>
<TextToken>b</TextToken>
</AnchorEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..95)"" Text=""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b"" />
<Capture Name=""1"" Span=""[12..48)"" Text=""((?# case sensitive comparison)D\w+)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void ReferenceTest127()
{
Test(@"@""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.""", @"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>{</TextToken>
</SimpleEscape>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>,</TextToken>
</Text>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>-</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>:</TextToken>
</SimpleEscape>
<LazyQuantifier>
<ClosedRangeNumericQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<OpenBraceToken>{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""4"">4</NumberToken>
<CloseBraceToken>}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>}</TextToken>
</SimpleEscape>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>x</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
</Sequence>
<EndOfFile>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia># Looks for a composite format item.</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..80)"" Text=""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."" />
<Capture Name=""1"" Span=""[15..23)"" Text=""(,-*\d+)"" />
<Capture Name=""2"" Span=""[24..36)"" Text=""(\:\w{1,4}?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/Core/Portable/Wrapping/Edit.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.PooledObjects;
namespace Microsoft.CodeAnalysis.Wrapping
{
/// <summary>
/// Represents an edit between two tokens. Specifically, provides the new trailing trivia for
/// the <see cref="Left"/> token and the new leading trivia for the <see
/// cref="Right"/> token.
/// </summary>
internal readonly struct Edit
{
public readonly SyntaxToken Left;
public readonly SyntaxToken Right;
public readonly SyntaxTriviaList NewLeftTrailingTrivia;
public readonly SyntaxTriviaList NewRightLeadingTrivia;
private Edit(
SyntaxToken left, SyntaxTriviaList newLeftTrailingTrivia,
SyntaxToken right, SyntaxTriviaList newRightLeadingTrivia)
{
Left = left;
Right = right;
NewLeftTrailingTrivia = newLeftTrailingTrivia;
NewRightLeadingTrivia = newRightLeadingTrivia;
}
public string GetNewTrivia()
{
var result = PooledStringBuilder.GetInstance();
AppendTrivia(result, NewLeftTrailingTrivia);
AppendTrivia(result, NewRightLeadingTrivia);
return result.ToStringAndFree();
}
private static void AppendTrivia(PooledStringBuilder result, SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
{
result.Builder.Append(trivia.ToFullString());
}
}
/// <summary>
/// Create the Edit representing the deletion of all trivia between left and right.
/// </summary>
public static Edit DeleteBetween(SyntaxNodeOrToken left, SyntaxNodeOrToken right)
=> UpdateBetween(left, default, default(SyntaxTriviaList), right);
public static Edit UpdateBetween(
SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia,
SyntaxTrivia rightLeadingTrivia, SyntaxNodeOrToken right)
{
return UpdateBetween(left, leftTrailingTrivia, new SyntaxTriviaList(rightLeadingTrivia), right);
}
public static Edit UpdateBetween(
SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia,
SyntaxTriviaList rightLeadingTrivia, SyntaxNodeOrToken right)
{
var leftLastToken = left.IsToken ? left.AsToken() : left.AsNode().GetLastToken();
var rightFirstToken = right.IsToken ? right.AsToken() : right.AsNode().GetFirstToken();
return new Edit(leftLastToken, leftTrailingTrivia, rightFirstToken, rightLeadingTrivia);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.PooledObjects;
namespace Microsoft.CodeAnalysis.Wrapping
{
/// <summary>
/// Represents an edit between two tokens. Specifically, provides the new trailing trivia for
/// the <see cref="Left"/> token and the new leading trivia for the <see
/// cref="Right"/> token.
/// </summary>
internal readonly struct Edit
{
public readonly SyntaxToken Left;
public readonly SyntaxToken Right;
public readonly SyntaxTriviaList NewLeftTrailingTrivia;
public readonly SyntaxTriviaList NewRightLeadingTrivia;
private Edit(
SyntaxToken left, SyntaxTriviaList newLeftTrailingTrivia,
SyntaxToken right, SyntaxTriviaList newRightLeadingTrivia)
{
Left = left;
Right = right;
NewLeftTrailingTrivia = newLeftTrailingTrivia;
NewRightLeadingTrivia = newRightLeadingTrivia;
}
public string GetNewTrivia()
{
var result = PooledStringBuilder.GetInstance();
AppendTrivia(result, NewLeftTrailingTrivia);
AppendTrivia(result, NewRightLeadingTrivia);
return result.ToStringAndFree();
}
private static void AppendTrivia(PooledStringBuilder result, SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
{
result.Builder.Append(trivia.ToFullString());
}
}
/// <summary>
/// Create the Edit representing the deletion of all trivia between left and right.
/// </summary>
public static Edit DeleteBetween(SyntaxNodeOrToken left, SyntaxNodeOrToken right)
=> UpdateBetween(left, default, default(SyntaxTriviaList), right);
public static Edit UpdateBetween(
SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia,
SyntaxTrivia rightLeadingTrivia, SyntaxNodeOrToken right)
{
return UpdateBetween(left, leftTrailingTrivia, new SyntaxTriviaList(rightLeadingTrivia), right);
}
public static Edit UpdateBetween(
SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia,
SyntaxTriviaList rightLeadingTrivia, SyntaxNodeOrToken right)
{
var leftLastToken = left.IsToken ? left.AsToken() : left.AsNode().GetLastToken();
var rightFirstToken = right.IsToken ? right.AsToken() : right.AsNode().GetFirstToken();
return new Edit(leftLastToken, leftTrailingTrivia, rightFirstToken, rightLeadingTrivia);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUsingStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IUsingStatement : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_SimpleUsingNewVariable()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (var c = new C())
{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }')
Locals: Local_1: C c
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.AsyncStreams)]
[Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")]
public void IUsingAwaitStatement_SimpleAwaitUsing()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
public static async Task M1(IAsyncDisposable disposable)
{
/*<bind>*/await using (var c = disposable)
{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (IsAsynchronous) (OperationKind.Using, Type: null) (Syntax: 'await using ... }')
Locals: Local_1: System.IAsyncDisposable c
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = disposable')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = disposable')
Declarators:
IVariableDeclaratorOperation (Symbol: System.IAsyncDisposable c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = disposable')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= disposable')
IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable')
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.AsyncStreams)]
[Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")]
public void UsingFlow_SimpleAwaitUsing()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
public static async Task M1(IAsyncDisposable disposable)
/*<bind>*/{
await using (var c = disposable)
{
Console.WriteLine(c.ToString());
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.IAsyncDisposable c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Right:
IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = disposable')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = disposable')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsImplicit) (Syntax: 'c = disposable')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_MultipleNewVariable()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (C c1 = new C(), c2 = new C())
{
Console.WriteLine(c1.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (C c1 ... }')
Locals: Local_1: C c1
Local_2: C c2
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'C c1 = new ... 2 = new C()')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c1 = new ... 2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_SimpleUsingStatementExistingResource()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
var c = new C();
/*<bind>*/using (c)
{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c) ... }')
Resources:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_NestedUsingNewResources()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (var c1 = new C())
using (var c2 = new C())
{
Console.WriteLine(c1.ToString() + c2.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }')
Locals: Local_1: C c1
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c1 = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }')
Locals: Local_1: C c2
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c2 = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_NestedUsingExistingResources()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
var c1 = new C();
var c2 = new C();
/*<bind>*/using (c1)
using (c2)
{
Console.WriteLine(c1.ToString() + c2.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c1) ... }')
Resources:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Body:
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c2) ... }')
Resources:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidMultipleVariableDeclaration()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (var c1 = new C(), c2 = new C())
{
Console.WriteLine(c1.ToString() + c2.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }')
Locals: Local_1: C c1
Local_2: C c2
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = ne ... 2 = new C()')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = ne ... 2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0819: Implicitly-typed variables cannot have multiple declarators
// /*<bind>*/using (var c1 = new C(), c2 = new C())
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C(), c2 = new C()").WithLocation(12, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IOperationTests_MultipleExistingResourcesPassed()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
/*<bind>*/{
var c1 = new C();
var c2 = new C();
using (c1, c2)
{
Console.WriteLine(c1.ToString() + c2.ToString());
}
}/*</bind>*/
}
";
// Capturing the whole block here, to show that the using statement is actually being bound as a using statement, followed by
// an expression and a separate block, rather than being bound as a using statement with an invalid expression as the resources
string expectedOperationTree = @"
IBlockOperation (5 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
Locals: Local_1: C c1
Local_2: C c2
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c1 = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c2 = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1')
Resources:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1')
Body:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c2')
Expression:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1026: ) expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_CloseParenExpected, ",").WithLocation(14, 18),
// CS1525: Invalid expression term ','
// using (c1, c2)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(14, 18),
// CS1002: ; expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ",").WithLocation(14, 18),
// CS1513: } expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_RbraceExpected, ",").WithLocation(14, 18),
// CS1002: ; expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(14, 22),
// CS1513: } expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(14, 22)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidNonDisposableNewResource()
{
string source = @"
using System;
class C
{
public static void M1()
{
/*<bind>*/using (var c1 = new C())
{
Console.WriteLine(c1.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }')
Locals: Local_1: C c1
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// /*<bind>*/using (var c1 = new C())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var c1 = new C()").WithArguments("C").WithLocation(9, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidNonDisposableExistingResource()
{
string source = @"
using System;
class C
{
public static void M1()
{
var c1 = new C();
/*<bind>*/using (c1)
{
Console.WriteLine(c1.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1) ... }')
Resources:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// /*<bind>*/using (c1)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1").WithArguments("C").WithLocation(10, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidEmptyUsingResources()
{
string source = @"
using System;
class C
{
public static void M1()
{
/*<bind>*/using ()
{
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using () ... }')
Resources:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term ')'
// /*<bind>*/using ()
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(9, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingWithoutSavedReference()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (GetC())
{
}/*</bind>*/
}
public static C GetC() => new C();
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (GetC ... }')
Resources:
IInvocationOperation (C C.GetC()) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()')
Instance Receiver:
null
Arguments(0)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DynamicArgument()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
dynamic d = null;
/*<bind>*/using (d)
{
Console.WriteLine(d);
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (d) ... }')
Resources:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(d);')
Expression:
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Console.WriteLine(d)')
Expression:
IDynamicMemberReferenceOperation (Member Name: ""WriteLine"", Containing Type: System.Console) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Console.WriteLine')
Type Arguments(0)
Instance Receiver:
null
Arguments(1):
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_NullResource()
{
string source = @"
using System;
class C
{
public static void M1()
{
/*<bind>*/using (null)
{
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (null ... }')
Resources:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_Declaration()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
using (/*<bind>*/var c = new C()/*</bind>*/)
{
Console.WriteLine(c.ToString());
}
}
}
";
string expectedOperationTree = @"
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_StatementSyntax()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
using (var c = new C())
/*<bind>*/{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_ExpressionSyntax()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
var c = new C();
using (/*<bind>*/c/*</bind>*/)
{
Console.WriteLine(c.ToString());
}
}
}
";
string expectedOperationTree = @"
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_VariableDeclaratorSyntax()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
using (C /*<bind>*/c1 = new C()/*</bind>*/, c2 = new C())
{
Console.WriteLine(c1.ToString());
}
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_OutVarInResource()
{
string source = @"
class P : System.IDisposable
{
public void Dispose()
{
}
void M(P p)
{
/*<bind>*/using (p = M2(out int c))
{
c = 1;
}/*</bind>*/
}
P M2(out int c)
{
c = 0;
return new P();
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (p = ... }')
Locals: Local_1: System.Int32 c
Resources:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p')
Right:
IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c')
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: '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)
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DefaultDisposeArguments()
{
string source = @"
class C
{
public static void M1()
{
/*<bind>*/using(var s = new S())
{
}/*</bind>*/
}
}
ref struct S
{
public void Dispose(int a = 1, bool b = true, params object[] others) { }
}
";
string expectedOperationTree = @"
IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(var s ... }')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(var s ... }')
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.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_ExpressionDefaultDisposeArguments()
{
string source = @"
class C
{
public static void M1()
{
var s = new S();
/*<bind>*/using(s)
{
}/*</bind>*/
}
}
ref struct S
{
public void Dispose(int a = 1, bool b = true, params object[] others) { }
}
";
string expectedOperationTree = @"
IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(s) ... }')
Resources:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(s) ... }')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(s) ... }')
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.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(s) ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(s) ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithDefaultParams()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
}
}
ref struct S
{
public void Dispose(params object[] extras = null) { }
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// file.cs(19,25): error CS1751: Cannot specify a default value for a parameter array
// public void Dispose(params object[] extras = null) { }
Diagnostic(ErrorCode.ERR_DefaultValueForParamsParameter, "params").WithLocation(19, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
//THEORY: we won't ever call a params in normal form, because we ignore the default value in metadata.
// So: it's either a valid params parameter, in which case we call it in the extended way.
// Or its an invalid params parameter, in which case we can't use it, and we error out.
// Interestingly we check params before we check default, so a params int = 3 will be callable with an
// argument, but not without.
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithDefaultParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] object[] extras
) cil managed
{
.param [1] = nullref
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics();
var verifier = CompileAndVerify(compilation);
verifier.VerifyIL("C.M2", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: call ""object[] System.Array.Empty<object>()""
IL_000f: call ""void S.Dispose(params object[])""
IL_0014: ret
}
");
verifier.VerifyIL("C.M1", @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
.try
{
IL_0008: leave.s IL_0017
}
finally
{
IL_000a: ldloca.s V_0
IL_000c: call ""object[] System.Array.Empty<object>()""
IL_0011: call ""void S.Dispose(params object[])""
IL_0016: endfinally
}
IL_0017: ret
}
");
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithNonArrayParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
s.Dispose(1);
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
int32 extras
) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithNonArrayOptionalParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
s.Dispose(1);
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] int32 extras
) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithNonArrayDefaultParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
s.Dispose(1);
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] int32 extras
) cil managed
{
.param [1] = int32(3)
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithDefaultParamsNotLast_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] object[] extras,
[opt] int32 a
) cil managed
{
.param [1] = nullref
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.param [2] = int32(0)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_01()
{
string source = @"
class P
{
void M(System.IDisposable input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
System.IDisposable GetDisposable() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( System.IDisposable P.GetDisposable()) (OperationKind.Invocation, Type: System.IDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_02()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
class MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_03()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (b ? GetDisposable() : input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
struct MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
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: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_04()
{
string source = @"
class P
{
void M<MyDisposable>(MyDisposable input, bool b) where MyDisposable : System.IDisposable
/*<bind>*/{
using (b ? GetDisposable<MyDisposable>() : input)
{
b = true;
}
}/*</bind>*/
T GetDisposable<T>() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
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: 'GetDisposab ... sposable>()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposab ... sposable>()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposab ... Disposable>')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_05()
{
string source = @"
class P
{
void M(MyDisposable? input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable? GetDisposable() => throw null;
}
struct MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_06()
{
string source = @"
class P
{
void M(dynamic input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
dynamic GetDisposable() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
CaptureIds: [2]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( dynamic P.GetDisposable()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitDynamic)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R4} {R5}
}
.try {R4, R5}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B9]
Finalizing: {R6}
Leaving: {R5} {R4} {R1}
}
.finally {R6}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B9] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_07()
{
string source = @"
class P
{
void M(NotDisposable input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
NotDisposable GetDisposable() => throw null;
}
class NotDisposable
{
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( NotDisposable P.GetDisposable()) (OperationKind.Invocation, Type: NotDisposable, IsInvalid) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: NotDisposable, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ExplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'NotDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (GetDisposable() ?? input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("NotDisposable").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_08()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (b ? GetDisposable() : input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
struct MyDisposable
{
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (b ? GetDisposable() : input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable() : input").WithArguments("MyDisposable").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_09()
{
string source = @"
class P
{
void M<MyDisposable>(MyDisposable input, bool b)
/*<bind>*/{
using (b ? GetDisposable<MyDisposable>() : input)
{
b = true;
}
}/*</bind>*/
T GetDisposable<T>() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... sposable>()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposab ... sposable>()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... Disposable>')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Unboxing)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (b ? GetDisposable<MyDisposable>() : input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable<MyDisposable>() : input").WithArguments("MyDisposable").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_10()
{
string source = @"
class P
{
void M(MyDisposable? input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable? GetDisposable() => throw null;
}
struct MyDisposable
{
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?, IsInvalid) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'MyDisposable?': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (GetDisposable() ?? input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("MyDisposable?").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_11()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (var x = GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
class MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
Locals: [MyDisposable x]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R4} {R5}
}
.try {R4, R5}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B9]
Finalizing: {R6}
Leaving: {R5} {R4} {R1}
}
.finally {R6}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B9] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_12()
{
string source = @"
class P
{
void M(dynamic input1, dynamic input2, bool b)
/*<bind>*/{
using (dynamic x = input1, y = input2)
{
b = true;
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [dynamic x] [dynamic y]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'x = input1')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1')
Right:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x = input1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitDynamic)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1')
Next (Regular) Block[B3]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'y = input2')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2')
Right:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input2')
Next (Regular) Block[B4]
Entering: {R5}
.locals {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y = input2')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitDynamic)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2')
Next (Regular) Block[B5]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B12]
Finalizing: {R8} {R9}
Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1}
}
.finally {R8}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = input2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = input2')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
.finally {R9}
{
Block[B9] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B11]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = input1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = input1')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1')
Arguments(0)
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
Block[B12] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_13()
{
string source = @"
class P
{
void M(System.IDisposable input, object o)
/*<bind>*/{
using (input)
{
o?.ToString();
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o')
Value:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();')
Expression:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Arguments(0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_14()
{
string source = @"
class P : System.IDisposable
{
public void Dispose()
{
}
void M(System.IDisposable input, P p)
/*<bind>*/{
using (p = M2(out int c))
{
c = 1;
}
}/*</bind>*/
P M2(out int c)
{
c = 0;
return new P();
}
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 c]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p = M2(out int c)')
Value:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p')
Right:
IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c')
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: '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[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'p = M2(out int c)')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'p = M2(out int c)')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'p = M2(out int c)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_15()
{
string source = @"
class P
{
void M(System.IDisposable input, object o)
/*<bind>*/{
using (input)
{
o?.ToString();
}
}/*</bind>*/
}
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o')
Value:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();')
Expression:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Arguments(0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'input')
Children(1):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_16()
{
string source = @"
class P
{
void M()
/*<bind>*/{
using (null)
{
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B4]
Block[B4] - Block [UnReachable]
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'null')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingFlow_17()
{
string source = @"
#pragma warning disable CS0815, CS0219
using System.Threading.Tasks;
class C
{
async Task M(S? s)
/*<bind>*/{
await using (s)
{
}
}/*</bind>*/
}
struct S
{
public Task DisposeAsync()
{
return default;
}
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
Value:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: S?, IsInvalid) (Syntax: 's')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 's')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 's')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// (9,22): error CS8410: 'S?': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (s)
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "s").WithArguments("S?").WithLocation(9, 22)
};
var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes });
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_18()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(int a = 3, bool b = false) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false])) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Arguments(2):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}')
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]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_19()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(int a = 3, bool b = false, params int[] extras) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false], params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}')
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.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_20()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(params int[] extras) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync(params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_21()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 'this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 'this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ExplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// file.cs(8,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'C.DisposeAsync(int, params int[], bool)'
// await using(this){}
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "this").WithArguments("extras", "C.DisposeAsync(int, params int[], bool)").WithLocation(8, 21),
// file.cs(8,21): error CS8410: 'C': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using(this){}
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "this").WithArguments("C").WithLocation(8, 21),
// file.cs(11,34): error CS0231: A params parameter must be the last parameter in a formal parameter list
// Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null;
Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] extras").WithLocation(11, 34)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_01()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using var x = new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_02()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using P x = new P(), y = new P(), z = new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x] [P y] [P z]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'z = new P()')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Next (Regular) Block[B14]
Finalizing: {R8} {R9} {R10}
Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1}
}
.finally {R8}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z = new P()')
Operand:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'z = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'z = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R9}
{
Block[B8] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B10]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()')
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Arguments(0)
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B8] [B9]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R10}
{
Block[B11] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B13]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B11] [B12]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B14] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_03()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using P x = null ?? new P(), y = new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
Locals: [P x] [P y]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block [UnReachable]
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()')
Value:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R4} {R5}
}
.try {R4, R5}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B6]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B6] - Block
Predecessors: [B5]
Statements (0)
Next (Regular) Block[B13]
Finalizing: {R8} {R9}
Leaving: {R7} {R6} {R5} {R4} {R1}
}
.finally {R8}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()')
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R9}
{
Block[B10] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = null ?? new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = null ?? new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = null ?? new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Arguments(0)
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B10] [B11]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B13] - Exit
Predecessors: [B6]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_04()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using P x = new P(), y = null ?? new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x] [P y]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3} {R4} {R5}
.try {R2, R3}
{
.locals {R4}
{
CaptureIds: [1]
.locals {R5}
{
CaptureIds: [0]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R5}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R5}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()')
Value:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()')
Next (Regular) Block[B6]
Leaving: {R4}
Entering: {R6} {R7}
}
.try {R6, R7}
{
Block[B6] - Block
Predecessors: [B5]
Statements (0)
Next (Regular) Block[B13]
Finalizing: {R8} {R9}
Leaving: {R7} {R6} {R3} {R2} {R1}
}
.finally {R8}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = null ?? new P()')
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = null ?? new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = null ?? new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R9}
{
Block[B10] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B10] [B11]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B13] - Exit
Predecessors: [B6]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_05()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
using var c = new P();
int d = 2;
using var e = new P();
int f = 3;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_06()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
using var c = new P();
int d = 2;
System.Action lambda = () => { _ = c.ToString(); };
using var e = new P();
int f = 3;
lambda();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [System.Action lambda] [P e] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }')
Left:
ILocalReferenceOperation: lambda (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { _ = ... String(); }')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '() => { _ = ... String(); }')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = c.ToString();')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: '_ = c.ToString()')
Left:
IDiscardOperation (Symbol: System.String _) (OperationKind.Discard, Type: System.String) (Syntax: '_')
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P) (Syntax: 'c')
Arguments(0)
Next (Regular) Block[B2#A0]
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'lambda();')
Expression:
IInvocationOperation (virtual void System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'lambda()')
Instance Receiver:
ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Action) (Syntax: 'lambda')
Arguments(0)
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_07()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
using var b = new P();
{
int c = 1;
using var d = new P();
int e = 2;
}
int f = 3;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [P b] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3} {R4}
.try {R2, R3}
{
.locals {R4}
{
Locals: [System.Int32 c] [P d] [System.Int32 e]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R5} {R6}
.try {R5, R6}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B7]
Finalizing: {R7}
Leaving: {R6} {R5} {R4}
}
.finally {R7}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()')
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B11]
Finalizing: {R8}
Leaving: {R3} {R2} {R1}
}
.finally {R8}
{
Block[B8] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B10]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()')
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Arguments(0)
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B8] [B9]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B11] - Exit
Predecessors: [B7]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_08()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
using var b = new P();
label1:
{
int c = 1;
if (a > 0)
goto label1;
using var d = new P();
if (a > 0)
goto label1;
int e = 2;
}
int f = 3;
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [P b] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3] [B5] [B10]
Statements (0)
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [System.Int32 c] [P d] [System.Int32 e]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0')
Left:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R4}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Entering: {R5} {R6}
.try {R5, R6}
{
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0')
Left:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Finalizing: {R7}
Leaving: {R6} {R5} {R4}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B10]
Finalizing: {R7}
Leaving: {R6} {R5} {R4}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()')
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Block
Predecessors: [B6]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B2]
}
.finally {R8}
{
Block[B11] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B13]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()')
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Arguments(0)
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B11] [B12]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B14] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_09()
{
string source = @"
#pragma warning disable CS0815, CS0219
using System.Threading.Tasks;
class C
{
public Task DisposeAsync()
{
return default;
}
async Task M()
/*<bind>*/{
await using var c = new C();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = new C()')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'c = new C()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes });
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics);
}
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_10()
{
string source = @"
#pragma warning disable CS0815, CS0219
using System.Threading.Tasks;
class C : System.IDisposable
{
public Task DisposeAsync()
{
return default;
}
public void Dispose()
{
}
async Task M()
/*<bind>*/{
using var c = new C();
await using var d = new C();
using var e = new C();
await using var f = new C();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c] [C d] [C e] [C f]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'd = new C()')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'e = new C()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'f = new C()')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Entering: {R8} {R9}
.try {R8, R9}
{
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Next (Regular) Block[B18]
Finalizing: {R10} {R11} {R12} {R13}
Leaving: {R9} {R8} {R7} {R6} {R5} {R4} {R3} {R2} {R1}
}
.finally {R10}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'f = new C()')
Operand:
ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'f = new C()')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'f = new C()')
Instance Receiver:
ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R11}
{
Block[B9] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B11]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new C()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new C()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new C()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()')
Arguments(0)
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R12}
{
Block[B12] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B14]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new C()')
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()')
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B12]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'd = new C()')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'd = new C()')
Instance Receiver:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()')
Arguments(0)
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R13}
{
Block[B15] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new C()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new C()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Arguments(0)
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B18] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes });
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_11()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
using var c = new P();
int d = 2;
using var e = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_12()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
label1:
using var c = new P();
int d = 2;
label2:
label3:
using var e = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_13()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
if (true)
label1:
using var a = new P();
if (true)
label2:
label3:
using var b = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B7]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [P a]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B13]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Entering: {R5}
.locals {R5}
{
Locals: [P b]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B9]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B9] - Block
Predecessors: [B8]
Statements (0)
Next (Regular) Block[B13]
Finalizing: {R8}
Leaving: {R7} {R6} {R5}
}
.finally {R8}
{
Block[B10] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Arguments(0)
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B10] [B11]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B13] - Exit
Predecessors: [B7] [B9]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label1:
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label1:
using var a = new P();").WithLocation(12, 13),
// file.cs(15,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label2:
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label2:
label3:
using var b = new P();").WithLocation(15, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_14()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
goto label1;
int x = 0;
label1:
using var a = this;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B0] [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(12,9): warning CS0162: Unreachable code detected
// int x = 0;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_15()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
label1:
using var a = this;
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P a]
Block[B1] - Block
Predecessors: [B0] [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B1]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(13,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(13, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_16()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
goto label1;
int x = 0;
label1:
using var a = this;
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B0] [B1] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B2]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(12,9): warning CS0162: Unreachable code detected
// int x = 0;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9),
// file.cs(15,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(15, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_17()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
if (b)
goto label1;
int x = 0;
label1:
using var a = this;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Next (Regular) Block[B8]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_18()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
label1:
using var a = this;
if (b)
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P a]
Block[B1] - Block
Predecessors: [B0] [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B6]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B1]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(14,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(14, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_19()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
if (b)
goto label1;
int x = 0;
label1:
using var a = this;
if (b)
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B8]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(17,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(17, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_20()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
ref struct P
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void P.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_21()
{
string source = @"
ref struct P
{
public object Dispose() => null;
void M(bool b)
/*<bind>*/{
using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// file.cs(8,13): warning CS0280: 'P' does not implement the 'disposable' pattern. 'P.Dispose()' has the wrong signature.
// using var x = new P();
Diagnostic(ErrorCode.WRN_PatternBadSignature, "using var x = new P();").WithArguments("P", "disposable", "P.Dispose()").WithLocation(8, 13),
// file.cs(8,13): error CS1674: 'P': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using var x = new P();
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x = new P();").WithArguments("P").WithLocation(8, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_22()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
ref struct P
{
public void Dispose(int a = 1, bool b = true, params object[] extras)
{
}
void M(bool b)
/*<bind>*/{
using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void P.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var x = new P();')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var x = new P();')
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.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var x = new P();')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var x = new P();')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_23()
{
string source = @"
using System.Threading.Tasks;
class P
{
public virtual Task DisposeAsync() => throw null;
async Task M(bool b)
/*<bind>*/{
await using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_24()
{
string source = @"
using System.Threading.Tasks;
class P
{
public virtual Task DisposeAsync(int a = 1, bool b = true, params object[] extras) => throw null;
async Task M(bool b)
/*<bind>*/{
await using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'await using ... = new P();')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'await using ... = new P();')
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.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'await using ... = new P();')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using ... = new P();')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using var c = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_MultipleDeclarations()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
/*<bind>*/{
using var c = new C();
using var d = new C();
using var e = new C();
} /*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C c
Local_2: C d
Local_3: C e
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var d = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var d = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var e = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var e = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration_MultipleVariables()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using C c = new C(), d = new C(), e = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = ... = new C();')
IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_MultipleDeclaration_WithLabels()
{
string source = @"
using System;
#pragma warning disable CS0164
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
/*<bind>*/{
label1:
using var a = new C();
label2:
label3:
using var b = new C();
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (2 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C a
Local_2: C b
ILabeledOperation (Label: label1) (OperationKind.Labeled, Type: null) (Syntax: 'label1: ... = new C();')
Statement:
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var a = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var a = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
ILabeledOperation (Label: label2) (OperationKind.Labeled, Type: null) (Syntax: 'label2: ... = new C();')
Statement:
ILabeledOperation (Label: label3) (OperationKind.Labeled, Type: null) (Syntax: 'label3: ... = new C();')
Statement:
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var b = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var b = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var b = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration_Async()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C
{
public Task DisposeAsync()
{
return default;
}
public static async Task M1()
{
/*<bind>*/await using var c = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_MultipleDeclarations_Async()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C
{
public Task DisposeAsync()
{
return default;
}
public static async Task M1()
/*<bind>*/{
await using var c = new C();
await using var d = new C();
await using var e = new C();
} /*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C c
Local_2: C d
Local_3: C e
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration_MultipleVariables_Async()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C
{
public Task DisposeAsync()
{
return default;
}
public static async Task M1()
{
/*<bind>*/await using C c = new C(), d = new C(), e = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_RegularAsync_Mix()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C : IDisposable
{
public Task DisposeAsync()
{
return default;
}
public void Dispose()
{
}
public static async Task M1()
/*<bind>*/{
using C c = new C();
await using C d = new C();
using C e = new C(), f = new C();
await using C g = new C(), h = new C();
} /*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements, 6 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C c
Local_2: C d
Local_3: C e
Local_4: C f
Local_5: C g
Local_6: C h
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C d = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C e = ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C e = ... = new C();')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C e = new C ... f = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C f) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'f = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C g = new C ... h = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C g) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'g = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C h) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'h = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UsingDeclaration_DefaultDisposeArguments()
{
string source = @"
class C
{
public static void M1()
{
/*<bind>*/using var s = new S();/*</bind>*/
}
}
ref struct S
{
public void Dispose(int a = 1, bool b = true, params object[] others) { }
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: False, DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var s = new S();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
DisposeArguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var s = new S();')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var s = new S();')
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.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var s = new S();')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var s = new S();')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_LocalFunctionDefinedAfterUsingReferenceBeforeUsing()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
/*<bind>*/{
localFunc2();
static void localFunc() {}
using IDisposable i = null;
localFunc();
static void localFunc2() {}
localFunc3();
static void localFunc3() {}
}/*</bind>*/
}
");
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @"
IBlockOperation (7 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.IDisposable i
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();')
Expression:
IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()')
Instance Receiver:
null
Arguments(0)
ILocalFunctionOperation (Symbol: void localFunc()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... alFunc() {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null')
Declarators:
IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();')
Expression:
IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()')
Instance Receiver:
null
Arguments(0)
ILocalFunctionOperation (Symbol: void localFunc2()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc2() {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();')
Expression:
IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()')
Instance Receiver:
null
Arguments(0)
ILocalFunctionOperation (Symbol: void localFunc3()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc3() {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
", DiagnosticDescription.None);
VerifyFlowGraphForTest<BlockSyntax>(comp, @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.IDisposable i]
Methods: [void localFunc()] [void localFunc2()] [void localFunc3()]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();')
Expression:
IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()')
Instance Receiver:
null
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();')
Expression:
IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()')
Instance Receiver:
null
Arguments(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();')
Expression:
IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null')
Instance Receiver:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
{ void localFunc()
Block[B0#0R1] - Entry
Statements (0)
Next (Regular) Block[B1#0R1]
Block[B1#0R1] - Exit
Predecessors: [B0#0R1]
Statements (0)
}
{ void localFunc2()
Block[B0#1R1] - Entry
Statements (0)
Next (Regular) Block[B1#1R1]
Block[B1#1R1] - Exit
Predecessors: [B0#1R1]
Statements (0)
}
{ void localFunc3()
Block[B0#2R1] - Entry
Statements (0)
Next (Regular) Block[B1#2R1]
Block[B1#2R1] - Exit
Predecessors: [B0#2R1]
Statements (0)
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void UsingDeclaration_LocalDefinedAfterUsingReferenceBeforeUsing()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
/*<bind>*/{
_ = local;
using IDisposable i = null;
object local = null;
}/*</bind>*/
}
");
var expectedDiagnostics = new DiagnosticDescription[] {
// (8,13): error CS0841: Cannot use local variable 'local' before it is declared
// _ = local;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "local").WithArguments("local").WithLocation(8, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @"
IBlockOperation (3 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
Locals: Local_1: System.IDisposable i
Local_2: System.Object local
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local')
Left:
IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_')
Right:
ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local')
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null')
Declarators:
IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'object local = null;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'object local = null')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Object local) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'local = null')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Initializer:
null
", expectedDiagnostics);
VerifyFlowGraphForTest<BlockSyntax>(comp, @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.IDisposable i] [System.Object local]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local')
Left:
IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_')
Right:
ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'local = null')
Left:
ILocalReferenceOperation: local (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'local = null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null')
Instance Receiver:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void UsingDeclaration_InsideSwitchCaseEmbeddedStatements()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M(int x)
/*<bind>*/{
switch (x)
{
case 5:
using C1 o1 = new C1();
break;
}
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(14,17): error CS8647: A using variable cannot be used directly within a switch section (consider using braces).
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_UsingVarInSwitchCase, "using C1 o1 = new C1();").WithLocation(14, 17)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [C1 o1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B8]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '5')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R2} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
Block[B8] - Exit
Predecessors: [B2] [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_InsideIfEmbeddedStatement()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M(bool b)
/*<bind>*/{
if (b)
using C1 o1 = new C1();
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(12, 13)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [C1 o1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B1] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_InsideForEmbeddedStatement()
{
var source = @"
using System;
using System.Collections;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M()
/*<bind>*/{
for (;;)
using C1 o1 = new C1();
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C1 o1]
Block[B1] - Block
Predecessors: [B0] [B6]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
Block[B7] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_InsideForEachEmbeddedStatement()
{
var source = @"
using System;
using System.Collections;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M(IEnumerable e)
/*<bind>*/{
foreach (var o in e)
using C1 o1 = new C1();
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e')
Value:
IInvocationOperation (virtual System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'e')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'e')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (0)
Jump if False (Regular) to Block[B12]
IInvocationOperation (virtual System.Boolean System.Collections.IEnumerator.MoveNext()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'e')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Arguments(0)
Finalizing: {R9}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [System.Object o]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'var')
Left:
ILocalReferenceOperation: o (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'var')
Right:
IPropertyReferenceOperation: System.Object System.Collections.IEnumerator.Current { get; } (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'var')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Next (Regular) Block[B4]
Entering: {R5}
.locals {R5}
{
Locals: [C1 o1]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Next (Regular) Block[B2]
Finalizing: {R8}
Leaving: {R7} {R6} {R5} {R4}
}
.finally {R8}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
}
.finally {R9}
{
CaptureIds: [1]
Block[B9] - Block
Predecessors (0)
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e')
Value:
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ExplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Jump if True (Regular) to Block[B11]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e')
Arguments(0)
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B12] - Exit
Predecessors: [B2]
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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IUsingStatement : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_SimpleUsingNewVariable()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (var c = new C())
{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }')
Locals: Local_1: C c
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.AsyncStreams)]
[Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")]
public void IUsingAwaitStatement_SimpleAwaitUsing()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
public static async Task M1(IAsyncDisposable disposable)
{
/*<bind>*/await using (var c = disposable)
{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (IsAsynchronous) (OperationKind.Using, Type: null) (Syntax: 'await using ... }')
Locals: Local_1: System.IAsyncDisposable c
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = disposable')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = disposable')
Declarators:
IVariableDeclaratorOperation (Symbol: System.IAsyncDisposable c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = disposable')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= disposable')
IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable')
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.AsyncStreams)]
[Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")]
public void UsingFlow_SimpleAwaitUsing()
{
string source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
public static async Task M1(IAsyncDisposable disposable)
/*<bind>*/{
await using (var c = disposable)
{
Console.WriteLine(c.ToString());
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.IAsyncDisposable c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Right:
IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = disposable')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = disposable')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsImplicit) (Syntax: 'c = disposable')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_MultipleNewVariable()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (C c1 = new C(), c2 = new C())
{
Console.WriteLine(c1.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (C c1 ... }')
Locals: Local_1: C c1
Local_2: C c2
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'C c1 = new ... 2 = new C()')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c1 = new ... 2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_SimpleUsingStatementExistingResource()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
var c = new C();
/*<bind>*/using (c)
{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c) ... }')
Resources:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_NestedUsingNewResources()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (var c1 = new C())
using (var c2 = new C())
{
Console.WriteLine(c1.ToString() + c2.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }')
Locals: Local_1: C c1
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c1 = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }')
Locals: Local_1: C c2
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c2 = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_NestedUsingExistingResources()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
var c1 = new C();
var c2 = new C();
/*<bind>*/using (c1)
using (c2)
{
Console.WriteLine(c1.ToString() + c2.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c1) ... }')
Resources:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Body:
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c2) ... }')
Resources:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidMultipleVariableDeclaration()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (var c1 = new C(), c2 = new C())
{
Console.WriteLine(c1.ToString() + c2.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }')
Locals: Local_1: C c1
Local_2: C c2
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = ne ... 2 = new C()')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = ne ... 2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0819: Implicitly-typed variables cannot have multiple declarators
// /*<bind>*/using (var c1 = new C(), c2 = new C())
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C(), c2 = new C()").WithLocation(12, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IOperationTests_MultipleExistingResourcesPassed()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
/*<bind>*/{
var c1 = new C();
var c2 = new C();
using (c1, c2)
{
Console.WriteLine(c1.ToString() + c2.ToString());
}
}/*</bind>*/
}
";
// Capturing the whole block here, to show that the using statement is actually being bound as a using statement, followed by
// an expression and a separate block, rather than being bound as a using statement with an invalid expression as the resources
string expectedOperationTree = @"
IBlockOperation (5 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
Locals: Local_1: C c1
Local_2: C c2
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c1 = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c2 = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1')
Resources:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1')
Body:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c2')
Expression:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()')
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()')
Instance Receiver:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1026: ) expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_CloseParenExpected, ",").WithLocation(14, 18),
// CS1525: Invalid expression term ','
// using (c1, c2)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(14, 18),
// CS1002: ; expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ",").WithLocation(14, 18),
// CS1513: } expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_RbraceExpected, ",").WithLocation(14, 18),
// CS1002: ; expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(14, 22),
// CS1513: } expected
// using (c1, c2)
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(14, 22)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidNonDisposableNewResource()
{
string source = @"
using System;
class C
{
public static void M1()
{
/*<bind>*/using (var c1 = new C())
{
Console.WriteLine(c1.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }')
Locals: Local_1: C c1
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = new C()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// /*<bind>*/using (var c1 = new C())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var c1 = new C()").WithArguments("C").WithLocation(9, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidNonDisposableExistingResource()
{
string source = @"
using System;
class C
{
public static void M1()
{
var c1 = new C();
/*<bind>*/using (c1)
{
Console.WriteLine(c1.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1) ... }')
Resources:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()')
Instance Receiver:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// /*<bind>*/using (c1)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1").WithArguments("C").WithLocation(10, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_InvalidEmptyUsingResources()
{
string source = @"
using System;
class C
{
public static void M1()
{
/*<bind>*/using ()
{
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using () ... }')
Resources:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term ')'
// /*<bind>*/using ()
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(9, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingWithoutSavedReference()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using (GetC())
{
}/*</bind>*/
}
public static C GetC() => new C();
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (GetC ... }')
Resources:
IInvocationOperation (C C.GetC()) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()')
Instance Receiver:
null
Arguments(0)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DynamicArgument()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
dynamic d = null;
/*<bind>*/using (d)
{
Console.WriteLine(d);
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (d) ... }')
Resources:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(d);')
Expression:
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Console.WriteLine(d)')
Expression:
IDynamicMemberReferenceOperation (Member Name: ""WriteLine"", Containing Type: System.Console) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Console.WriteLine')
Type Arguments(0)
Instance Receiver:
null
Arguments(1):
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_NullResource()
{
string source = @"
using System;
class C
{
public static void M1()
{
/*<bind>*/using (null)
{
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (null ... }')
Resources:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_Declaration()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
using (/*<bind>*/var c = new C()/*</bind>*/)
{
Console.WriteLine(c.ToString());
}
}
}
";
string expectedOperationTree = @"
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_StatementSyntax()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
using (var c = new C())
/*<bind>*/{
Console.WriteLine(c.ToString());
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()')
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_ExpressionSyntax()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
var c = new C();
using (/*<bind>*/c/*</bind>*/)
{
Console.WriteLine(c.ToString());
}
}
}
";
string expectedOperationTree = @"
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_UsingStatementSyntax_VariableDeclaratorSyntax()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
using (C /*<bind>*/c1 = new C()/*</bind>*/, c2 = new C())
{
Console.WriteLine(c1.ToString());
}
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_OutVarInResource()
{
string source = @"
class P : System.IDisposable
{
public void Dispose()
{
}
void M(P p)
{
/*<bind>*/using (p = M2(out int c))
{
c = 1;
}/*</bind>*/
}
P M2(out int c)
{
c = 0;
return new P();
}
}
";
string expectedOperationTree = @"
IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (p = ... }')
Locals: Local_1: System.Int32 c
Resources:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p')
Right:
IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c')
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: '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)
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DefaultDisposeArguments()
{
string source = @"
class C
{
public static void M1()
{
/*<bind>*/using(var s = new S())
{
}/*</bind>*/
}
}
ref struct S
{
public void Dispose(int a = 1, bool b = true, params object[] others) { }
}
";
string expectedOperationTree = @"
IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(var s ... }')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(var s ... }')
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.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_ExpressionDefaultDisposeArguments()
{
string source = @"
class C
{
public static void M1()
{
var s = new S();
/*<bind>*/using(s)
{
}/*</bind>*/
}
}
ref struct S
{
public void Dispose(int a = 1, bool b = true, params object[] others) { }
}
";
string expectedOperationTree = @"
IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(s) ... }')
Resources:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(s) ... }')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(s) ... }')
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.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(s) ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(s) ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(s) ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithDefaultParams()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
}
}
ref struct S
{
public void Dispose(params object[] extras = null) { }
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// file.cs(19,25): error CS1751: Cannot specify a default value for a parameter array
// public void Dispose(params object[] extras = null) { }
Diagnostic(ErrorCode.ERR_DefaultValueForParamsParameter, "params").WithLocation(19, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
//THEORY: we won't ever call a params in normal form, because we ignore the default value in metadata.
// So: it's either a valid params parameter, in which case we call it in the extended way.
// Or its an invalid params parameter, in which case we can't use it, and we error out.
// Interestingly we check params before we check default, so a params int = 3 will be callable with an
// argument, but not without.
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithDefaultParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] object[] extras
) cil managed
{
.param [1] = nullref
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics();
var verifier = CompileAndVerify(compilation);
verifier.VerifyIL("C.M2", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: call ""object[] System.Array.Empty<object>()""
IL_000f: call ""void S.Dispose(params object[])""
IL_0014: ret
}
");
verifier.VerifyIL("C.M1", @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
.try
{
IL_0008: leave.s IL_0017
}
finally
{
IL_000a: ldloca.s V_0
IL_000c: call ""object[] System.Array.Empty<object>()""
IL_0011: call ""void S.Dispose(params object[])""
IL_0016: endfinally
}
IL_0017: ret
}
");
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
DisposeArguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithNonArrayParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
s.Dispose(1);
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
int32 extras
) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithNonArrayOptionalParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
s.Dispose(1);
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] int32 extras
) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithNonArrayDefaultParams_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
s.Dispose(1);
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] int32 extras
) cil managed
{
.param [1] = int32(3)
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void IUsingStatement_DisposalWithDefaultParamsNotLast_Metadata()
{
string source = @"
class C
{
public static void M1()
/*<bind>*/{
using(var s = new S())
{
}
}/*</bind>*/
public static void M2()
{
var s = new S();
s.Dispose();
}
}
";
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.method public hidebysig
instance void Dispose (
[opt] object[] extras,
[opt] int32 a
) cil managed
{
.param [1] = nullref
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
01 00 00 00
)
.param [2] = int32(0)
.maxstack 8
IL_0000: nop
IL_0001: ret
}
}
";
var ilReference = CreateMetadataReferenceFromIlSource(ilSource);
var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
// (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)'
// s.Dispose();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(14, 11)
};
var compilation = CreateCompilationWithIL(source, ilSource);
compilation.VerifyDiagnostics(expectedDiagnostics);
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }')
Locals: Local_1: S s
Resources:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics);
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [S s]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Left:
ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Right:
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_01()
{
string source = @"
class P
{
void M(System.IDisposable input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
System.IDisposable GetDisposable() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( System.IDisposable P.GetDisposable()) (OperationKind.Invocation, Type: System.IDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_02()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
class MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_03()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (b ? GetDisposable() : input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
struct MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
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: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_04()
{
string source = @"
class P
{
void M<MyDisposable>(MyDisposable input, bool b) where MyDisposable : System.IDisposable
/*<bind>*/{
using (b ? GetDisposable<MyDisposable>() : input)
{
b = true;
}
}/*</bind>*/
T GetDisposable<T>() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
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: 'GetDisposab ... sposable>()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposab ... sposable>()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposab ... Disposable>')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_05()
{
string source = @"
class P
{
void M(MyDisposable? input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable? GetDisposable() => throw null;
}
struct MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_06()
{
string source = @"
class P
{
void M(dynamic input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
dynamic GetDisposable() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
CaptureIds: [2]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( dynamic P.GetDisposable()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitDynamic)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R4} {R5}
}
.try {R4, R5}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B9]
Finalizing: {R6}
Leaving: {R5} {R4} {R1}
}
.finally {R6}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B9] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_07()
{
string source = @"
class P
{
void M(NotDisposable input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
NotDisposable GetDisposable() => throw null;
}
class NotDisposable
{
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( NotDisposable P.GetDisposable()) (OperationKind.Invocation, Type: NotDisposable, IsInvalid) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: NotDisposable, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ExplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'NotDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (GetDisposable() ?? input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("NotDisposable").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_08()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (b ? GetDisposable() : input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
struct MyDisposable
{
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (b ? GetDisposable() : input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable() : input").WithArguments("MyDisposable").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_09()
{
string source = @"
class P
{
void M<MyDisposable>(MyDisposable input, bool b)
/*<bind>*/{
using (b ? GetDisposable<MyDisposable>() : input)
{
b = true;
}
}/*</bind>*/
T GetDisposable<T>() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... sposable>()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposab ... sposable>()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... Disposable>')
Arguments(0)
Next (Regular) Block[B4]
Entering: {R2} {R3}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Unboxing)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (b ? GetDisposable<MyDisposable>() : input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable<MyDisposable>() : input").WithArguments("MyDisposable").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_10()
{
string source = @"
class P
{
void M(MyDisposable? input, bool b)
/*<bind>*/{
using (GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable? GetDisposable() => throw null;
}
struct MyDisposable
{
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?, IsInvalid) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R2}
Entering: {R3} {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?, IsInvalid) (Syntax: 'input')
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,16): error CS1674: 'MyDisposable?': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (GetDisposable() ?? input)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("MyDisposable?").WithLocation(6, 16)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_11()
{
string source = @"
class P
{
void M(MyDisposable input, bool b)
/*<bind>*/{
using (var x = GetDisposable() ?? input)
{
b = true;
}
}/*</bind>*/
MyDisposable GetDisposable() => throw null;
}
class MyDisposable : System.IDisposable
{
public void Dispose() => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
Locals: [MyDisposable x]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable')
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R4} {R5}
}
.try {R4, R5}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B9]
Finalizing: {R6}
Leaving: {R5} {R4} {R1}
}
.finally {R6}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B9] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_12()
{
string source = @"
class P
{
void M(dynamic input1, dynamic input2, bool b)
/*<bind>*/{
using (dynamic x = input1, y = input2)
{
b = true;
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [dynamic x] [dynamic y]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'x = input1')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1')
Right:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x = input1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitDynamic)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1')
Next (Regular) Block[B3]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'y = input2')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2')
Right:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input2')
Next (Regular) Block[B4]
Entering: {R5}
.locals {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y = input2')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitDynamic)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2')
Next (Regular) Block[B5]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B12]
Finalizing: {R8} {R9}
Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1}
}
.finally {R8}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = input2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = input2')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
.finally {R9}
{
Block[B9] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B11]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = input1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = input1')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1')
Arguments(0)
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
Block[B12] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_13()
{
string source = @"
class P
{
void M(System.IDisposable input, object o)
/*<bind>*/{
using (input)
{
o?.ToString();
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o')
Value:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();')
Expression:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Arguments(0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_14()
{
string source = @"
class P : System.IDisposable
{
public void Dispose()
{
}
void M(System.IDisposable input, P p)
/*<bind>*/{
using (p = M2(out int c))
{
c = 1;
}
}/*</bind>*/
P M2(out int c)
{
c = 0;
return new P();
}
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 c]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p = M2(out int c)')
Value:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p')
Right:
IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c')
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: '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[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'p = M2(out int c)')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'p = M2(out int c)')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'p = M2(out int c)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_15()
{
string source = @"
class P
{
void M(System.IDisposable input, object o)
/*<bind>*/{
using (input)
{
o?.ToString();
}
}/*</bind>*/
}
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o')
Value:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();')
Expression:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Arguments(0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'input')
Children(1):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_16()
{
string source = @"
class P
{
void M()
/*<bind>*/{
using (null)
{
}
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B4]
Block[B4] - Block [UnReachable]
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'null')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingFlow_17()
{
string source = @"
#pragma warning disable CS0815, CS0219
using System.Threading.Tasks;
class C
{
async Task M(S? s)
/*<bind>*/{
await using (s)
{
}
}/*</bind>*/
}
struct S
{
public Task DisposeAsync()
{
return default;
}
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
Value:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: S?, IsInvalid) (Syntax: 's')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 's')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 's')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// (9,22): error CS8410: 'S?': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (s)
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "s").WithArguments("S?").WithLocation(9, 22)
};
var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes });
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_18()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(int a = 3, bool b = false) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false])) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Arguments(2):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}')
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]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_19()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(int a = 3, bool b = false, params int[] extras) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false], params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}')
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.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_20()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(params int[] extras) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync(params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingFlow_21()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task M()
/*<bind>*/{
await using(this){}
}/*</bind>*/
Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'this')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'this')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 'this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 'this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ExplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// file.cs(8,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'C.DisposeAsync(int, params int[], bool)'
// await using(this){}
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "this").WithArguments("extras", "C.DisposeAsync(int, params int[], bool)").WithLocation(8, 21),
// file.cs(8,21): error CS8410: 'C': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using(this){}
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "this").WithArguments("C").WithLocation(8, 21),
// file.cs(11,34): error CS0231: A params parameter must be the last parameter in a formal parameter list
// Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null;
Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] extras").WithLocation(11, 34)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_01()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using var x = new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_02()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using P x = new P(), y = new P(), z = new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x] [P y] [P z]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'z = new P()')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Next (Regular) Block[B14]
Finalizing: {R8} {R9} {R10}
Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1}
}
.finally {R8}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z = new P()')
Operand:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'z = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'z = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R9}
{
Block[B8] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B10]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()')
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Arguments(0)
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B8] [B9]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R10}
{
Block[B11] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B13]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B11] [B12]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B14] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_03()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using P x = null ?? new P(), y = new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
Locals: [P x] [P y]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block [UnReachable]
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()')
Value:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R4} {R5}
}
.try {R4, R5}
{
Block[B5] - Block
Predecessors: [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B6]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B6] - Block
Predecessors: [B5]
Statements (0)
Next (Regular) Block[B13]
Finalizing: {R8} {R9}
Leaving: {R7} {R6} {R5} {R4} {R1}
}
.finally {R8}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()')
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R9}
{
Block[B10] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = null ?? new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = null ?? new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = null ?? new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()')
Arguments(0)
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B10] [B11]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B13] - Exit
Predecessors: [B6]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_04()
{
string source = @"
using System;
class P : IDisposable
{
void M()
/*<bind>*/{
using P x = new P(), y = null ?? new P();
}/*</bind>*/
public void Dispose() { }
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x] [P y]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3} {R4} {R5}
.try {R2, R3}
{
.locals {R4}
{
CaptureIds: [1]
.locals {R5}
{
CaptureIds: [0]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R5}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R5}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()')
Value:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Left:
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()')
Next (Regular) Block[B6]
Leaving: {R4}
Entering: {R6} {R7}
}
.try {R6, R7}
{
Block[B6] - Block
Predecessors: [B5]
Statements (0)
Next (Regular) Block[B13]
Finalizing: {R8} {R9}
Leaving: {R7} {R6} {R3} {R2} {R1}
}
.finally {R8}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = null ?? new P()')
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = null ?? new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = null ?? new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R9}
{
Block[B10] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B10] [B11]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B13] - Exit
Predecessors: [B6]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_05()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
using var c = new P();
int d = 2;
using var e = new P();
int f = 3;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_06()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
using var c = new P();
int d = 2;
System.Action lambda = () => { _ = c.ToString(); };
using var e = new P();
int f = 3;
lambda();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [System.Action lambda] [P e] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }')
Left:
ILocalReferenceOperation: lambda (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { _ = ... String(); }')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '() => { _ = ... String(); }')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = c.ToString();')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: '_ = c.ToString()')
Left:
IDiscardOperation (Symbol: System.String _) (OperationKind.Discard, Type: System.String) (Syntax: '_')
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P) (Syntax: 'c')
Arguments(0)
Next (Regular) Block[B2#A0]
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'lambda();')
Expression:
IInvocationOperation (virtual void System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'lambda()')
Instance Receiver:
ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Action) (Syntax: 'lambda')
Arguments(0)
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_07()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
using var b = new P();
{
int c = 1;
using var d = new P();
int e = 2;
}
int f = 3;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [P b] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3} {R4}
.try {R2, R3}
{
.locals {R4}
{
Locals: [System.Int32 c] [P d] [System.Int32 e]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R5} {R6}
.try {R5, R6}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B7]
Finalizing: {R7}
Leaving: {R6} {R5} {R4}
}
.finally {R7}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()')
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B11]
Finalizing: {R8}
Leaving: {R3} {R2} {R1}
}
.finally {R8}
{
Block[B8] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B10]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()')
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Arguments(0)
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B8] [B9]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B11] - Exit
Predecessors: [B7]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_08()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
using var b = new P();
label1:
{
int c = 1;
if (a > 0)
goto label1;
using var d = new P();
if (a > 0)
goto label1;
int e = 2;
}
int f = 3;
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [P b] [System.Int32 f]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3] [B5] [B10]
Statements (0)
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [System.Int32 c] [P d] [System.Int32 e]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0')
Left:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R4}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Entering: {R5} {R6}
.try {R5, R6}
{
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0')
Left:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Finalizing: {R7}
Leaving: {R6} {R5} {R4}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B10]
Finalizing: {R7}
Leaving: {R6} {R5} {R4}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()')
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Block
Predecessors: [B6]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B2]
}
.finally {R8}
{
Block[B11] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B13]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()')
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()')
Arguments(0)
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B11] [B12]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B14] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_09()
{
string source = @"
#pragma warning disable CS0815, CS0219
using System.Threading.Tasks;
class C
{
public Task DisposeAsync()
{
return default;
}
async Task M()
/*<bind>*/{
await using var c = new C();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = new C()')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'c = new C()')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes });
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics);
}
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_10()
{
string source = @"
#pragma warning disable CS0815, CS0219
using System.Threading.Tasks;
class C : System.IDisposable
{
public Task DisposeAsync()
{
return default;
}
public void Dispose()
{
}
async Task M()
/*<bind>*/{
using var c = new C();
await using var d = new C();
using var e = new C();
await using var f = new C();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c] [C d] [C e] [C f]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'd = new C()')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'e = new C()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'f = new C()')
Left:
ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Entering: {R8} {R9}
.try {R8, R9}
{
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Next (Regular) Block[B18]
Finalizing: {R10} {R11} {R12} {R13}
Leaving: {R9} {R8} {R7} {R6} {R5} {R4} {R3} {R2} {R1}
}
.finally {R10}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'f = new C()')
Operand:
ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'f = new C()')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'f = new C()')
Instance Receiver:
ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R11}
{
Block[B9] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B11]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new C()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new C()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new C()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()')
Arguments(0)
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R12}
{
Block[B12] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B14]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new C()')
Operand:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()')
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B12]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'd = new C()')
Expression:
IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'd = new C()')
Instance Receiver:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()')
Arguments(0)
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R13}
{
Block[B15] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new C()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new C()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Arguments(0)
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B18] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes });
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_Flow_11()
{
string source = @"
#pragma warning disable CS0815, CS0219
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
using var c = new P();
int d = 2;
using var e = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_12()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
int a = 0;
int b = 1;
label1:
using var c = new P();
int d = 2;
label2:
label3:
using var e = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Left:
ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()')
Left:
ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R4} {R5}
.try {R4, R5}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B10]
Finalizing: {R6} {R7}
Leaving: {R5} {R4} {R3} {R2} {R1}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()')
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
.finally {R7}
{
Block[B7] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()')
Arguments(0)
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B10] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_13()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
if (true)
label1:
using var a = new P();
if (true)
label2:
label3:
using var b = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B7]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [P a]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B13]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B8]
Entering: {R5}
.locals {R5}
{
Locals: [P b]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B9]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B9] - Block
Predecessors: [B8]
Statements (0)
Next (Regular) Block[B13]
Finalizing: {R8}
Leaving: {R7} {R6} {R5}
}
.finally {R8}
{
Block[B10] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()')
Arguments(0)
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B10] [B11]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B13] - Exit
Predecessors: [B7] [B9]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label1:
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label1:
using var a = new P();").WithLocation(12, 13),
// file.cs(15,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label2:
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label2:
label3:
using var b = new P();").WithLocation(15, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_14()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
goto label1;
int x = 0;
label1:
using var a = this;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B0] [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(12,9): warning CS0162: Unreachable code detected
// int x = 0;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_15()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
label1:
using var a = this;
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P a]
Block[B1] - Block
Predecessors: [B0] [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B1]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(13,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(13, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_16()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M()
/*<bind>*/{
goto label1;
int x = 0;
label1:
using var a = this;
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B0] [B1] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B2]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(12,9): warning CS0162: Unreachable code detected
// int x = 0;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9),
// file.cs(15,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(15, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_17()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
if (b)
goto label1;
int x = 0;
label1:
using var a = this;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Next (Regular) Block[B8]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_18()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
label1:
using var a = this;
if (b)
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P a]
Block[B1] - Block
Predecessors: [B0] [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B6]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B1]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(14,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(14, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_19()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
class P : System.IDisposable
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
if (b)
goto label1;
int x = 0;
label1:
using var a = this;
if (b)
goto label1;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 x] [P a]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this')
Left:
ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Right:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this')
Next (Regular) Block[B4]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B8]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Finalizing: {R4}
Leaving: {R3} {R2}
}
.finally {R4}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this')
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B8] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = new[]{
// file.cs(17,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(17, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_20()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
ref struct P
{
public void Dispose()
{
}
void M(bool b)
/*<bind>*/{
using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void P.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_21()
{
string source = @"
ref struct P
{
public object Dispose() => null;
void M(bool b)
/*<bind>*/{
using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = new[]
{
// file.cs(8,13): warning CS0280: 'P' does not implement the 'disposable' pattern. 'P.Dispose()' has the wrong signature.
// using var x = new P();
Diagnostic(ErrorCode.WRN_PatternBadSignature, "using var x = new P();").WithArguments("P", "disposable", "P.Dispose()").WithLocation(8, 13),
// file.cs(8,13): error CS1674: 'P': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using var x = new P();
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x = new P();").WithArguments("P").WithLocation(8, 13)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_22()
{
string source = @"
#pragma warning disable CS0815, CS0219, CS0164
ref struct P
{
public void Dispose(int a = 1, bool b = true, params object[] extras)
{
}
void M(bool b)
/*<bind>*/{
using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B4]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IInvocationOperation ( void P.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var x = new P();')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var x = new P();')
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.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var x = new P();')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var x = new P();')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var x = new P();')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_23()
{
string source = @"
using System.Threading.Tasks;
class P
{
public virtual Task DisposeAsync() => throw null;
async Task M(bool b)
/*<bind>*/{
await using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void UsingDeclaration_Flow_24()
{
string source = @"
using System.Threading.Tasks;
class P
{
public virtual Task DisposeAsync(int a = 1, bool b = true, params object[] extras) => throw null;
async Task M(bool b)
/*<bind>*/{
await using var x = new P();
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [P x]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Right:
IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()')
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()')
Expression:
IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'await using ... = new P();')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'await using ... = new P();')
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.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'await using ... = new P();')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using ... = new P();')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using ... = new P();')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using var c = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_MultipleDeclarations()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
/*<bind>*/{
using var c = new C();
using var d = new C();
using var e = new C();
} /*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C c
Local_2: C d
Local_3: C e
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var d = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var d = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var e = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var e = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration_MultipleVariables()
{
string source = @"
using System;
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
{
/*<bind>*/using C c = new C(), d = new C(), e = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = ... = new C();')
IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_MultipleDeclaration_WithLabels()
{
string source = @"
using System;
#pragma warning disable CS0164
class C : IDisposable
{
public void Dispose()
{
}
public static void M1()
/*<bind>*/{
label1:
using var a = new C();
label2:
label3:
using var b = new C();
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (2 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C a
Local_2: C b
ILabeledOperation (Label: label1) (OperationKind.Labeled, Type: null) (Syntax: 'label1: ... = new C();')
Statement:
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var a = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var a = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
ILabeledOperation (Label: label2) (OperationKind.Labeled, Type: null) (Syntax: 'label2: ... = new C();')
Statement:
ILabeledOperation (Label: label3) (OperationKind.Labeled, Type: null) (Syntax: 'label3: ... = new C();')
Statement:
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var b = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var b = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var b = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration_Async()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C
{
public Task DisposeAsync()
{
return default;
}
public static async Task M1()
{
/*<bind>*/await using var c = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_MultipleDeclarations_Async()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C
{
public Task DisposeAsync()
{
return default;
}
public static async Task M1()
/*<bind>*/{
await using var c = new C();
await using var d = new C();
await using var e = new C();
} /*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C c
Local_2: C d
Local_3: C e
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_SingleDeclaration_MultipleVariables_Async()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C
{
public Task DisposeAsync()
{
return default;
}
public static async Task M1()
{
/*<bind>*/await using C c = new C(), d = new C(), e = new C();/*</bind>*/
}
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")]
public void UsingDeclaration_RegularAsync_Mix()
{
string source = @"
using System;
using System.Threading.Tasks;
namespace System { interface IAsyncDisposable { } }
class C : IDisposable
{
public Task DisposeAsync()
{
return default;
}
public void Dispose()
{
}
public static async Task M1()
/*<bind>*/{
using C c = new C();
await using C d = new C();
using C e = new C(), f = new C();
await using C g = new C(), h = new C();
} /*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements, 6 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: C c
Local_2: C d
Local_3: C e
Local_4: C f
Local_5: C g
Local_6: C h
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C d = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C e = ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C e = ... = new C();')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C e = new C ... f = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C f) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'f = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();')
IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C g = new C ... h = new C()')
Declarators:
IVariableDeclaratorOperation (Symbol: C g) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'g = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IVariableDeclaratorOperation (Symbol: C h) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'h = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()')
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UsingDeclaration_DefaultDisposeArguments()
{
string source = @"
class C
{
public static void M1()
{
/*<bind>*/using var s = new S();/*</bind>*/
}
}
ref struct S
{
public void Dispose(int a = 1, bool b = true, params object[] others) { }
}
";
string expectedOperationTree = @"
IUsingDeclarationOperation(IsAsynchronous: False, DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var s = new S();')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()')
Declarators:
IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()')
IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()')
Arguments(0)
Initializer:
null
Initializer:
null
DisposeArguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var s = new S();')
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.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var s = new S();')
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.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var s = new S();')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var s = new S();')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var s = new S();')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_LocalFunctionDefinedAfterUsingReferenceBeforeUsing()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
/*<bind>*/{
localFunc2();
static void localFunc() {}
using IDisposable i = null;
localFunc();
static void localFunc2() {}
localFunc3();
static void localFunc3() {}
}/*</bind>*/
}
");
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @"
IBlockOperation (7 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.IDisposable i
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();')
Expression:
IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()')
Instance Receiver:
null
Arguments(0)
ILocalFunctionOperation (Symbol: void localFunc()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... alFunc() {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null')
Declarators:
IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();')
Expression:
IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()')
Instance Receiver:
null
Arguments(0)
ILocalFunctionOperation (Symbol: void localFunc2()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc2() {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();')
Expression:
IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()')
Instance Receiver:
null
Arguments(0)
ILocalFunctionOperation (Symbol: void localFunc3()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc3() {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
", DiagnosticDescription.None);
VerifyFlowGraphForTest<BlockSyntax>(comp, @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.IDisposable i]
Methods: [void localFunc()] [void localFunc2()] [void localFunc3()]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();')
Expression:
IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()')
Instance Receiver:
null
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();')
Expression:
IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()')
Instance Receiver:
null
Arguments(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();')
Expression:
IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null')
Instance Receiver:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
{ void localFunc()
Block[B0#0R1] - Entry
Statements (0)
Next (Regular) Block[B1#0R1]
Block[B1#0R1] - Exit
Predecessors: [B0#0R1]
Statements (0)
}
{ void localFunc2()
Block[B0#1R1] - Entry
Statements (0)
Next (Regular) Block[B1#1R1]
Block[B1#1R1] - Exit
Predecessors: [B0#1R1]
Statements (0)
}
{ void localFunc3()
Block[B0#2R1] - Entry
Statements (0)
Next (Regular) Block[B1#2R1]
Block[B1#2R1] - Exit
Predecessors: [B0#2R1]
Statements (0)
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void UsingDeclaration_LocalDefinedAfterUsingReferenceBeforeUsing()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
/*<bind>*/{
_ = local;
using IDisposable i = null;
object local = null;
}/*</bind>*/
}
");
var expectedDiagnostics = new DiagnosticDescription[] {
// (8,13): error CS0841: Cannot use local variable 'local' before it is declared
// _ = local;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "local").WithArguments("local").WithLocation(8, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @"
IBlockOperation (3 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }')
Locals: Local_1: System.IDisposable i
Local_2: System.Object local
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local')
Left:
IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_')
Right:
ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local')
IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;')
DeclarationGroup:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null')
Declarators:
IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'object local = null;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'object local = null')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Object local) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'local = null')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Initializer:
null
", expectedDiagnostics);
VerifyFlowGraphForTest<BlockSyntax>(comp, @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.IDisposable i] [System.Object local]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local')
Left:
IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_')
Right:
ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'local = null')
Left:
ILocalReferenceOperation: local (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'local = null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null')
Instance Receiver:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void UsingDeclaration_InsideSwitchCaseEmbeddedStatements()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M(int x)
/*<bind>*/{
switch (x)
{
case 5:
using C1 o1 = new C1();
break;
}
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(14,17): error CS8647: A using variable cannot be used directly within a switch section (consider using braces).
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_UsingVarInSwitchCase, "using C1 o1 = new C1();").WithLocation(14, 17)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [C1 o1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B8]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '5')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B4]
Entering: {R3} {R4}
.try {R3, R4}
{
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Next (Regular) Block[B8]
Finalizing: {R5}
Leaving: {R4} {R3} {R2} {R1}
}
.finally {R5}
{
Block[B5] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
Block[B8] - Exit
Predecessors: [B2] [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_InsideIfEmbeddedStatement()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M(bool b)
/*<bind>*/{
if (b)
using C1 o1 = new C1();
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(12, 13)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [C1 o1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B3]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B7]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B1] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_InsideForEmbeddedStatement()
{
var source = @"
using System;
using System.Collections;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M()
/*<bind>*/{
for (;;)
using C1 o1 = new C1();
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C1 o1]
Block[B1] - Block
Predecessors: [B0] [B6]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Regular) Block[B6]
Finalizing: {R4}
Leaving: {R3} {R2} {R1}
}
.finally {R4}
{
Block[B3] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B6] - Block
Predecessors: [B2]
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
Block[B7] - Exit [UnReachable]
Predecessors (0)
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void UsingDeclaration_InsideForEachEmbeddedStatement()
{
var source = @"
using System;
using System.Collections;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void M(IEnumerable e)
/*<bind>*/{
foreach (var o in e)
using C1 o1 = new C1();
}/*</bind>*/
}";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13)
};
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e')
Value:
IInvocationOperation (virtual System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'e')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'e')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (0)
Jump if False (Regular) to Block[B12]
IInvocationOperation (virtual System.Boolean System.Collections.IEnumerator.MoveNext()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'e')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Arguments(0)
Finalizing: {R9}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [System.Object o]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'var')
Left:
ILocalReferenceOperation: o (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'var')
Right:
IPropertyReferenceOperation: System.Object System.Collections.IEnumerator.Current { get; } (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'var')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Next (Regular) Block[B4]
Entering: {R5}
.locals {R5}
{
Locals: [C1 o1]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Left:
ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B5]
Entering: {R6} {R7}
.try {R6, R7}
{
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Next (Regular) Block[B2]
Finalizing: {R8}
Leaving: {R7} {R6} {R5} {R4}
}
.finally {R8}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
}
}
.finally {R9}
{
CaptureIds: [1]
Block[B9] - Block
Predecessors (0)
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e')
Value:
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ExplicitReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e')
Jump if True (Regular) to Block[B11]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e')
Arguments(0)
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B12] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/CSharpTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.CSharp.ReplaceDocCommentTextWithTag;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReplaceDocCommentTextWithTag
{
public class ReplaceDocCommentTextWithTagTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [||]null.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""null""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestEndOfKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword abstract[||].
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""abstract""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestEndOfKeyword_NewLineFollowing()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword static[||]
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""static""/>
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestSelectedKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [|abstract|].
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""abstract""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestInsideKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword asy[||]nc.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""async""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestNotInsideKeywordIfNonEmptySpan()
{
await TestMissingAsync(
@"
/// TKey must implement the System.IDisposable int[|erf|]ace
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Start()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the [||]System.IDisposable interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Mid1()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the System[||].IDisposable interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Mid2()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the System.[||]IDisposable interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_End()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the System.IDisposable[||] interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Selected()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the [|System.IDisposable|] interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestTypeParameterReference()
{
await TestInRegularAndScriptAsync(
@"
/// [||]TKey must implement the System.IDisposable interface.
class C<TKey>
{
}",
@"
/// <typeparamref name=""TKey""/> must implement the System.IDisposable interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestTypeParameterReference_EmptyClassBody()
{
await TestInRegularAndScriptAsync(
@"
/// [||]TKey must implement the System.IDisposable interface.
class C<TKey>{}",
@"
/// <typeparamref name=""TKey""/> must implement the System.IDisposable interface.
class C<TKey>{}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestCanSeeInnerMethod()
{
await TestInRegularAndScriptAsync(
@"
/// Use WriteLine[||] as a Console.WriteLine replacement
class C
{
void WriteLine<TKey>(TKey value) { }
}",
@"
/// Use <see cref=""WriteLine""/> as a Console.WriteLine replacement
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestNotOnMispelledName()
{
await TestMissingAsync(
@"
/// Use WriteLine1[||] as a Console.WriteLine replacement
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameterSymbol()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameterSymbol_EmptyBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameterSymbol_ExpressionBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameter_SemicolonBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
void WriteLine<TKey>(TKey value);
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
void WriteLine<TKey>(TKey value);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol_EmptyBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol_ExpressionBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol_SemicolonBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value);
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value);
}");
}
[WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestNonApplicableKeyword()
{
await TestMissingAsync(
@"
/// Testing keyword interfa[||]ce.
class C<TKey>
{
}");
}
[WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestInXMLAttribute()
{
await TestMissingAsync(
@"
/// Testing keyword inside <see langword =""nu[||]ll""/>
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestInXMLAttribute2()
{
await TestMissingAsync(
@"
/// Testing keyword inside <see langword =""nu[||]ll""
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestBaseKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [||]base.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""base""/>.
class C<TKey>
{
}");
}
[WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestThisKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [||]this.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""this""/>.
class C<TKey>
{
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.CSharp.ReplaceDocCommentTextWithTag;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReplaceDocCommentTextWithTag
{
public class ReplaceDocCommentTextWithTagTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [||]null.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""null""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestEndOfKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword abstract[||].
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""abstract""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestEndOfKeyword_NewLineFollowing()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword static[||]
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""static""/>
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestSelectedKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [|abstract|].
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""abstract""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestInsideKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword asy[||]nc.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""async""/>.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestNotInsideKeywordIfNonEmptySpan()
{
await TestMissingAsync(
@"
/// TKey must implement the System.IDisposable int[|erf|]ace
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Start()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the [||]System.IDisposable interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Mid1()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the System[||].IDisposable interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Mid2()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the System.[||]IDisposable interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_End()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the System.IDisposable[||] interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestStartOfFullyQualifiedTypeName_Selected()
{
await TestInRegularAndScriptAsync(
@"
/// TKey must implement the [|System.IDisposable|] interface.
class C<TKey>
{
}",
@"
/// TKey must implement the <see cref=""System.IDisposable""/> interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestTypeParameterReference()
{
await TestInRegularAndScriptAsync(
@"
/// [||]TKey must implement the System.IDisposable interface.
class C<TKey>
{
}",
@"
/// <typeparamref name=""TKey""/> must implement the System.IDisposable interface.
class C<TKey>
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestTypeParameterReference_EmptyClassBody()
{
await TestInRegularAndScriptAsync(
@"
/// [||]TKey must implement the System.IDisposable interface.
class C<TKey>{}",
@"
/// <typeparamref name=""TKey""/> must implement the System.IDisposable interface.
class C<TKey>{}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestCanSeeInnerMethod()
{
await TestInRegularAndScriptAsync(
@"
/// Use WriteLine[||] as a Console.WriteLine replacement
class C
{
void WriteLine<TKey>(TKey value) { }
}",
@"
/// Use <see cref=""WriteLine""/> as a Console.WriteLine replacement
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestNotOnMispelledName()
{
await TestMissingAsync(
@"
/// Use WriteLine1[||] as a Console.WriteLine replacement
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameterSymbol()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameterSymbol_EmptyBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameterSymbol_ExpressionBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodTypeParameter_SemicolonBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value has type TKey[||] so we don't box primitives.
void WriteLine<TKey>(TKey value);
}",
@"
class C
{
/// value has type <typeparamref name=""TKey""/> so we don't box primitives.
void WriteLine<TKey>(TKey value);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value) { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol_EmptyBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value){}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol_ExpressionBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
object WriteLine<TKey>(TKey value) => null;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestMethodParameterSymbol_SemicolonBody()
{
await TestInRegularAndScriptAsync(
@"
class C
{
/// value[||] has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value);
}",
@"
class C
{
/// <paramref name=""value""/> has type TKey so we don't box primitives.
void WriteLine<TKey>(TKey value);
}");
}
[WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestNonApplicableKeyword()
{
await TestMissingAsync(
@"
/// Testing keyword interfa[||]ce.
class C<TKey>
{
}");
}
[WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestInXMLAttribute()
{
await TestMissingAsync(
@"
/// Testing keyword inside <see langword =""nu[||]ll""/>
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestInXMLAttribute2()
{
await TestMissingAsync(
@"
/// Testing keyword inside <see langword =""nu[||]ll""
class C
{
void WriteLine<TKey>(TKey value) { }
}");
}
[WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestBaseKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [||]base.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""base""/>.
class C<TKey>
{
}");
}
[WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)]
public async Task TestThisKeyword()
{
await TestInRegularAndScriptAsync(
@"
/// Testing keyword [||]this.
class C<TKey>
{
}",
@"
/// Testing keyword <see langword=""this""/>.
class C<TKey>
{
}");
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpUseNotPatternTests.cs | // Licensed to the .NET Foundation under one or more 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.CSharp;
using Microsoft.CodeAnalysis.CSharp.UsePatternMatching;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching
{
using VerifyCS = CSharpCodeFixVerifier<
CSharpUseNotPatternDiagnosticAnalyzer,
CSharpUseNotPatternCodeFixProvider>;
public partial class CSharpUseNotPatternTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
[WorkItem(50690, "https://github.com/dotnet/roslyn/issues/50690")]
public async Task BinaryIsExpression()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x [|is|] string))
{
}
}
}",
FixedCode =
@"class C
{
void M(object x)
{
if (x is not string)
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
[WorkItem(50690, "https://github.com/dotnet/roslyn/issues/50690")]
public async Task ConstantPattern()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x [|is|] null))
{
}
}
}",
FixedCode =
@"class C
{
void M(object x)
{
if (x is not null)
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
[WorkItem(46699, "https://github.com/dotnet/roslyn/issues/46699")]
public async Task UseNotPattern()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x [|is|] string s))
{
}
}
}",
FixedCode =
@"class C
{
void M(object x)
{
if (x is not string s)
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
public async Task UnavailableInCSharp8()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x is string s))
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp8,
}.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.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UsePatternMatching;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching
{
using VerifyCS = CSharpCodeFixVerifier<
CSharpUseNotPatternDiagnosticAnalyzer,
CSharpUseNotPatternCodeFixProvider>;
public partial class CSharpUseNotPatternTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
[WorkItem(50690, "https://github.com/dotnet/roslyn/issues/50690")]
public async Task BinaryIsExpression()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x [|is|] string))
{
}
}
}",
FixedCode =
@"class C
{
void M(object x)
{
if (x is not string)
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
[WorkItem(50690, "https://github.com/dotnet/roslyn/issues/50690")]
public async Task ConstantPattern()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x [|is|] null))
{
}
}
}",
FixedCode =
@"class C
{
void M(object x)
{
if (x is not null)
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
[WorkItem(46699, "https://github.com/dotnet/roslyn/issues/46699")]
public async Task UseNotPattern()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x [|is|] string s))
{
}
}
}",
FixedCode =
@"class C
{
void M(object x)
{
if (x is not string s)
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNotPattern)]
public async Task UnavailableInCSharp8()
{
await new VerifyCS.Test
{
TestCode =
@"class C
{
void M(object x)
{
if (!(x is string s))
{
}
}
}",
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/SyntaxTokenClassifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers
{
internal class SyntaxTokenClassifier : AbstractSyntaxClassifier
{
public override ImmutableArray<int> SyntaxTokenKinds { get; } = ImmutableArray.Create((int)SyntaxKind.LessThanToken);
private static readonly Func<ITypeSymbol, bool> s_shouldInclude = t => t.TypeKind != TypeKind.Error && t.GetArity() > 0;
public override void AddClassifications(
Workspace workspace,
SyntaxToken lessThanToken,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
var syntaxTree = semanticModel.SyntaxTree;
if (syntaxTree.IsInPartiallyWrittenGeneric(lessThanToken.Span.End, cancellationToken, out var identifier))
{
// IsInPartiallyWrittenGeneric will return true for things that could be
// partially generic method calls (as opposed to partially written types).
//
// For example: X?.Y<
//
// In this case, this could never be a type, and we do not want to try to
// resolve it as such as it can lead to inappropriate classifications.
if (CouldBeGenericType(identifier))
{
var types = semanticModel.LookupTypeRegardlessOfArity(identifier, cancellationToken);
if (types.Any(s_shouldInclude))
{
#nullable disable // Can 'GetClassificationForType(types.First()' be null here?
result.Add(new ClassifiedSpan(identifier.Span, GetClassificationForType(types.First())));
#nullable enable
}
}
}
}
private static bool CouldBeGenericType(SyntaxToken identifier)
{
// Look for patterns that indicate that this could never be a partially written
// generic *Type* (although it could be a partially written generic method).
if (!(identifier.Parent is IdentifierNameSyntax identifierName))
{
// Definitely not a generic type if this isn't even an identifier name.
return false;
}
if (identifierName.IsParentKind(SyntaxKind.MemberBindingExpression))
{
// anything?.Identifier is never a generic type.
return false;
}
// ?.X.Identifier or ?.X.Y.Identifier is never a generic type.
if (identifierName.IsSimpleMemberAccessExpressionName() ||
identifierName.IsMemberBindingExpressionName())
{
if (identifier.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression))
return false;
}
// Add more cases as necessary.
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers
{
internal class SyntaxTokenClassifier : AbstractSyntaxClassifier
{
public override ImmutableArray<int> SyntaxTokenKinds { get; } = ImmutableArray.Create((int)SyntaxKind.LessThanToken);
private static readonly Func<ITypeSymbol, bool> s_shouldInclude = t => t.TypeKind != TypeKind.Error && t.GetArity() > 0;
public override void AddClassifications(
Workspace workspace,
SyntaxToken lessThanToken,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
var syntaxTree = semanticModel.SyntaxTree;
if (syntaxTree.IsInPartiallyWrittenGeneric(lessThanToken.Span.End, cancellationToken, out var identifier))
{
// IsInPartiallyWrittenGeneric will return true for things that could be
// partially generic method calls (as opposed to partially written types).
//
// For example: X?.Y<
//
// In this case, this could never be a type, and we do not want to try to
// resolve it as such as it can lead to inappropriate classifications.
if (CouldBeGenericType(identifier))
{
var types = semanticModel.LookupTypeRegardlessOfArity(identifier, cancellationToken);
if (types.Any(s_shouldInclude))
{
#nullable disable // Can 'GetClassificationForType(types.First()' be null here?
result.Add(new ClassifiedSpan(identifier.Span, GetClassificationForType(types.First())));
#nullable enable
}
}
}
}
private static bool CouldBeGenericType(SyntaxToken identifier)
{
// Look for patterns that indicate that this could never be a partially written
// generic *Type* (although it could be a partially written generic method).
if (!(identifier.Parent is IdentifierNameSyntax identifierName))
{
// Definitely not a generic type if this isn't even an identifier name.
return false;
}
if (identifierName.IsParentKind(SyntaxKind.MemberBindingExpression))
{
// anything?.Identifier is never a generic type.
return false;
}
// ?.X.Identifier or ?.X.Y.Identifier is never a generic type.
if (identifierName.IsSimpleMemberAccessExpressionName() ||
identifierName.IsMemberBindingExpressionName())
{
if (identifier.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression))
return false;
}
// Add more cases as necessary.
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/ChangeSignature/AddParameterDialog.xaml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Windows;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
{
/// <summary>
/// Interaction logic for AddParameterDialog.xaml
/// </summary>
internal partial class AddParameterDialog : DialogWindow
{
private readonly AddParameterDialogViewModel _viewModel;
public string OK { get { return ServicesVSResources.OK; } }
public string Cancel { get { return ServicesVSResources.Cancel; } }
public string ParameterInformation { get { return ServicesVSResources.Parameter_information; } }
public string TypeNameLabel { get { return ServicesVSResources.Type_Name; } }
public string ParameterNameLabel { get { return ServicesVSResources.Parameter_Name; } }
public string CallSiteValueLabel { get { return ServicesVSResources.Call_site_value; } }
public string AddParameterDialogTitle { get { return ServicesVSResources.Add_Parameter; } }
public string ParameterKind { get { return ServicesVSResources.Parameter_kind; } }
public string Required { get { return ServicesVSResources.Required; } }
public string OptionalWithDefaultValue { get { return ServicesVSResources.Optional_with_default_value_colon; } }
public string ValueToInjectAtCallsites { get { return ServicesVSResources.Value_to_inject_at_call_sites; } }
public string Value { get { return ServicesVSResources.Value_colon; } }
public string UseNamedArgument { get { return ServicesVSResources.Use_named_argument; } }
public string IntroduceUndefinedTodoVariables { get { return ServicesVSResources.IntroduceUndefinedTodoVariables; } }
public string OmitOnlyForOptionalParameters { get { return ServicesVSResources.Omit_only_for_optional_parameters; } }
public string InferFromContext { get { return ServicesVSResources.Infer_from_context; } }
public AddParameterDialog(AddParameterDialogViewModel viewModel)
{
_viewModel = viewModel;
this.Loaded += AddParameterDialog_Loaded;
DataContext = _viewModel;
InitializeComponent();
}
private void AddParameterDialog_Loaded(object sender, RoutedEventArgs e)
{
MinHeight = Height;
TypeContentControl.Focus();
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// Workaround WPF bug: https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1101094
DataContext = null;
}
private void OK_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly AddParameterDialog _dialog;
public TestAccessor(AddParameterDialog dialog)
{
_dialog = dialog;
}
public DialogButton OKButton => _dialog.OKButton;
public DialogButton CancelButton => _dialog.CancelButton;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Windows;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
{
/// <summary>
/// Interaction logic for AddParameterDialog.xaml
/// </summary>
internal partial class AddParameterDialog : DialogWindow
{
private readonly AddParameterDialogViewModel _viewModel;
public string OK { get { return ServicesVSResources.OK; } }
public string Cancel { get { return ServicesVSResources.Cancel; } }
public string ParameterInformation { get { return ServicesVSResources.Parameter_information; } }
public string TypeNameLabel { get { return ServicesVSResources.Type_Name; } }
public string ParameterNameLabel { get { return ServicesVSResources.Parameter_Name; } }
public string CallSiteValueLabel { get { return ServicesVSResources.Call_site_value; } }
public string AddParameterDialogTitle { get { return ServicesVSResources.Add_Parameter; } }
public string ParameterKind { get { return ServicesVSResources.Parameter_kind; } }
public string Required { get { return ServicesVSResources.Required; } }
public string OptionalWithDefaultValue { get { return ServicesVSResources.Optional_with_default_value_colon; } }
public string ValueToInjectAtCallsites { get { return ServicesVSResources.Value_to_inject_at_call_sites; } }
public string Value { get { return ServicesVSResources.Value_colon; } }
public string UseNamedArgument { get { return ServicesVSResources.Use_named_argument; } }
public string IntroduceUndefinedTodoVariables { get { return ServicesVSResources.IntroduceUndefinedTodoVariables; } }
public string OmitOnlyForOptionalParameters { get { return ServicesVSResources.Omit_only_for_optional_parameters; } }
public string InferFromContext { get { return ServicesVSResources.Infer_from_context; } }
public AddParameterDialog(AddParameterDialogViewModel viewModel)
{
_viewModel = viewModel;
this.Loaded += AddParameterDialog_Loaded;
DataContext = _viewModel;
InitializeComponent();
}
private void AddParameterDialog_Loaded(object sender, RoutedEventArgs e)
{
MinHeight = Height;
TypeContentControl.Focus();
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// Workaround WPF bug: https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1101094
DataContext = null;
}
private void OK_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly AddParameterDialog _dialog;
public TestAccessor(AddParameterDialog dialog)
{
_dialog = dialog;
}
public DialogButton OKButton => _dialog.OKButton;
public DialogButton CancelButton => _dialog.CancelButton;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Literal.cs | // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitLiteral(BoundLiteral node)
{
Debug.Assert(node.ConstantValue is { });
return MakeLiteral(node.Syntax, node.ConstantValue, node.Type, oldNodeOpt: node);
}
private BoundExpression MakeLiteral(SyntaxNode syntax, ConstantValue constantValue, TypeSymbol? type, BoundLiteral? oldNodeOpt = null)
{
Debug.Assert(constantValue != null);
if (constantValue.IsDecimal)
{
// Rewrite decimal literal
Debug.Assert(type is { SpecialType: SpecialType.System_Decimal });
return MakeDecimalLiteral(syntax, constantValue);
}
else if (constantValue.IsDateTime)
{
// C# does not support DateTime constants but VB does; we might have obtained a
// DateTime constant by calling a method with an optional parameter with a DateTime
// for its default value.
Debug.Assert(type is { SpecialType: SpecialType.System_DateTime });
return MakeDateTimeLiteral(syntax, constantValue);
}
else if (oldNodeOpt != null)
{
return oldNodeOpt.Update(constantValue, type);
}
else
{
return new BoundLiteral(syntax, constantValue, type, hasErrors: constantValue.IsBad);
}
}
private BoundExpression MakeDecimalLiteral(SyntaxNode syntax, ConstantValue constantValue)
{
Debug.Assert(constantValue != null);
Debug.Assert(constantValue.IsDecimal);
var value = constantValue.DecimalValue;
bool isNegative;
byte scale;
uint low, mid, high;
value.GetBits(out isNegative, out scale, out low, out mid, out high);
var arguments = new ArrayBuilder<BoundExpression>();
SpecialMember member;
// check if we can call a simpler constructor, or use a predefined constant
if (scale == 0 && int.MinValue <= value && value <= int.MaxValue)
{
// If we are building static constructor of System.Decimal, accessing static fields
// would be bad.
var curMethod = _factory.CurrentFunction;
Debug.Assert(curMethod is { });
if ((curMethod.MethodKind != MethodKind.SharedConstructor ||
curMethod.ContainingType.SpecialType != SpecialType.System_Decimal) &&
!_inExpressionLambda)
{
Symbol? useField = null;
if (value == decimal.Zero)
{
useField = _compilation.GetSpecialTypeMember(SpecialMember.System_Decimal__Zero);
}
else if (value == decimal.One)
{
useField = _compilation.GetSpecialTypeMember(SpecialMember.System_Decimal__One);
}
else if (value == decimal.MinusOne)
{
useField = _compilation.GetSpecialTypeMember(SpecialMember.System_Decimal__MinusOne);
}
if (useField is { HasUseSiteError: false, ContainingType: { HasUseSiteError: false } })
{
var fieldSymbol = (FieldSymbol)useField;
return new BoundFieldAccess(syntax, null, fieldSymbol, constantValue);
}
}
//new decimal(int);
member = SpecialMember.System_Decimal__CtorInt32;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((int)value), _compilation.GetSpecialType(SpecialType.System_Int32)));
}
else if (scale == 0 && uint.MinValue <= value && value <= uint.MaxValue)
{
//new decimal(uint);
member = SpecialMember.System_Decimal__CtorUInt32;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((uint)value), _compilation.GetSpecialType(SpecialType.System_UInt32)));
}
else if (scale == 0 && long.MinValue <= value && value <= long.MaxValue)
{
//new decimal(long);
member = SpecialMember.System_Decimal__CtorInt64;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((long)value), _compilation.GetSpecialType(SpecialType.System_Int64)));
}
else if (scale == 0 && ulong.MinValue <= value && value <= ulong.MaxValue)
{
//new decimal(ulong);
member = SpecialMember.System_Decimal__CtorUInt64;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((ulong)value), _compilation.GetSpecialType(SpecialType.System_UInt64)));
}
else
{
//new decimal(int low, int mid, int high, bool isNegative, byte scale);
member = SpecialMember.System_Decimal__CtorInt32Int32Int32BooleanByte;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(low), _compilation.GetSpecialType(SpecialType.System_Int32)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(mid), _compilation.GetSpecialType(SpecialType.System_Int32)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(high), _compilation.GetSpecialType(SpecialType.System_Int32)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(isNegative), _compilation.GetSpecialType(SpecialType.System_Boolean)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(scale), _compilation.GetSpecialType(SpecialType.System_Byte)));
}
var ctor = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member);
Debug.Assert((object)ctor != null);
Debug.Assert(ctor.ContainingType.SpecialType == SpecialType.System_Decimal);
return new BoundObjectCreationExpression(
syntax, ctor, arguments.ToImmutableAndFree(),
argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: default(ImmutableArray<RefKind>), expanded: false,
argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector),
constantValueOpt: constantValue, initializerExpressionOpt: null, type: ctor.ContainingType);
}
private BoundExpression MakeDateTimeLiteral(SyntaxNode syntax, ConstantValue constantValue)
{
Debug.Assert(constantValue != null);
Debug.Assert(constantValue.IsDateTime);
var arguments = new ArrayBuilder<BoundExpression>();
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(constantValue.DateTimeValue.Ticks), _compilation.GetSpecialType(SpecialType.System_Int64)));
var ctor = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(SpecialMember.System_DateTime__CtorInt64);
Debug.Assert((object)ctor != null);
Debug.Assert(ctor.ContainingType.SpecialType == SpecialType.System_DateTime);
// This is not a constant from C#'s perspective, so do not mark it as one.
return new BoundObjectCreationExpression(
syntax, ctor, arguments.ToImmutableAndFree(),
argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: default(ImmutableArray<RefKind>), expanded: false,
argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector),
constantValueOpt: ConstantValue.NotAvailable, initializerExpressionOpt: null, type: ctor.ContainingType);
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitLiteral(BoundLiteral node)
{
Debug.Assert(node.ConstantValue is { });
return MakeLiteral(node.Syntax, node.ConstantValue, node.Type, oldNodeOpt: node);
}
private BoundExpression MakeLiteral(SyntaxNode syntax, ConstantValue constantValue, TypeSymbol? type, BoundLiteral? oldNodeOpt = null)
{
Debug.Assert(constantValue != null);
if (constantValue.IsDecimal)
{
// Rewrite decimal literal
Debug.Assert(type is { SpecialType: SpecialType.System_Decimal });
return MakeDecimalLiteral(syntax, constantValue);
}
else if (constantValue.IsDateTime)
{
// C# does not support DateTime constants but VB does; we might have obtained a
// DateTime constant by calling a method with an optional parameter with a DateTime
// for its default value.
Debug.Assert(type is { SpecialType: SpecialType.System_DateTime });
return MakeDateTimeLiteral(syntax, constantValue);
}
else if (oldNodeOpt != null)
{
return oldNodeOpt.Update(constantValue, type);
}
else
{
return new BoundLiteral(syntax, constantValue, type, hasErrors: constantValue.IsBad);
}
}
private BoundExpression MakeDecimalLiteral(SyntaxNode syntax, ConstantValue constantValue)
{
Debug.Assert(constantValue != null);
Debug.Assert(constantValue.IsDecimal);
var value = constantValue.DecimalValue;
bool isNegative;
byte scale;
uint low, mid, high;
value.GetBits(out isNegative, out scale, out low, out mid, out high);
var arguments = new ArrayBuilder<BoundExpression>();
SpecialMember member;
// check if we can call a simpler constructor, or use a predefined constant
if (scale == 0 && int.MinValue <= value && value <= int.MaxValue)
{
// If we are building static constructor of System.Decimal, accessing static fields
// would be bad.
var curMethod = _factory.CurrentFunction;
Debug.Assert(curMethod is { });
if ((curMethod.MethodKind != MethodKind.SharedConstructor ||
curMethod.ContainingType.SpecialType != SpecialType.System_Decimal) &&
!_inExpressionLambda)
{
Symbol? useField = null;
if (value == decimal.Zero)
{
useField = _compilation.GetSpecialTypeMember(SpecialMember.System_Decimal__Zero);
}
else if (value == decimal.One)
{
useField = _compilation.GetSpecialTypeMember(SpecialMember.System_Decimal__One);
}
else if (value == decimal.MinusOne)
{
useField = _compilation.GetSpecialTypeMember(SpecialMember.System_Decimal__MinusOne);
}
if (useField is { HasUseSiteError: false, ContainingType: { HasUseSiteError: false } })
{
var fieldSymbol = (FieldSymbol)useField;
return new BoundFieldAccess(syntax, null, fieldSymbol, constantValue);
}
}
//new decimal(int);
member = SpecialMember.System_Decimal__CtorInt32;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((int)value), _compilation.GetSpecialType(SpecialType.System_Int32)));
}
else if (scale == 0 && uint.MinValue <= value && value <= uint.MaxValue)
{
//new decimal(uint);
member = SpecialMember.System_Decimal__CtorUInt32;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((uint)value), _compilation.GetSpecialType(SpecialType.System_UInt32)));
}
else if (scale == 0 && long.MinValue <= value && value <= long.MaxValue)
{
//new decimal(long);
member = SpecialMember.System_Decimal__CtorInt64;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((long)value), _compilation.GetSpecialType(SpecialType.System_Int64)));
}
else if (scale == 0 && ulong.MinValue <= value && value <= ulong.MaxValue)
{
//new decimal(ulong);
member = SpecialMember.System_Decimal__CtorUInt64;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create((ulong)value), _compilation.GetSpecialType(SpecialType.System_UInt64)));
}
else
{
//new decimal(int low, int mid, int high, bool isNegative, byte scale);
member = SpecialMember.System_Decimal__CtorInt32Int32Int32BooleanByte;
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(low), _compilation.GetSpecialType(SpecialType.System_Int32)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(mid), _compilation.GetSpecialType(SpecialType.System_Int32)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(high), _compilation.GetSpecialType(SpecialType.System_Int32)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(isNegative), _compilation.GetSpecialType(SpecialType.System_Boolean)));
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(scale), _compilation.GetSpecialType(SpecialType.System_Byte)));
}
var ctor = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(member);
Debug.Assert((object)ctor != null);
Debug.Assert(ctor.ContainingType.SpecialType == SpecialType.System_Decimal);
return new BoundObjectCreationExpression(
syntax, ctor, arguments.ToImmutableAndFree(),
argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: default(ImmutableArray<RefKind>), expanded: false,
argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector),
constantValueOpt: constantValue, initializerExpressionOpt: null, type: ctor.ContainingType);
}
private BoundExpression MakeDateTimeLiteral(SyntaxNode syntax, ConstantValue constantValue)
{
Debug.Assert(constantValue != null);
Debug.Assert(constantValue.IsDateTime);
var arguments = new ArrayBuilder<BoundExpression>();
arguments.Add(new BoundLiteral(syntax, ConstantValue.Create(constantValue.DateTimeValue.Ticks), _compilation.GetSpecialType(SpecialType.System_Int64)));
var ctor = (MethodSymbol)_compilation.Assembly.GetSpecialTypeMember(SpecialMember.System_DateTime__CtorInt64);
Debug.Assert((object)ctor != null);
Debug.Assert(ctor.ContainingType.SpecialType == SpecialType.System_DateTime);
// This is not a constant from C#'s perspective, so do not mark it as one.
return new BoundObjectCreationExpression(
syntax, ctor, arguments.ToImmutableAndFree(),
argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: default(ImmutableArray<RefKind>), expanded: false,
argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector),
constantValueOpt: ConstantValue.NotAvailable, initializerExpressionOpt: null, type: ctor.ContainingType);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/CSharp/Portable/Organizing/Organizers/IndexerDeclarationOrganizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer<IndexerDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public IndexerDeclarationOrganizer()
{
}
protected override IndexerDeclarationSyntax Organize(
IndexerDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
attributeLists: syntax.AttributeLists,
modifiers: ModifiersOrganizer.Organize(syntax.Modifiers),
type: syntax.Type,
explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier,
thisKeyword: syntax.ThisKeyword,
parameterList: syntax.ParameterList,
accessorList: syntax.AccessorList,
expressionBody: syntax.ExpressionBody,
semicolonToken: syntax.SemicolonToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer<IndexerDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public IndexerDeclarationOrganizer()
{
}
protected override IndexerDeclarationSyntax Organize(
IndexerDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
attributeLists: syntax.AttributeLists,
modifiers: ModifiersOrganizer.Organize(syntax.Modifiers),
type: syntax.Type,
explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier,
thisKeyword: syntax.ThisKeyword,
parameterList: syntax.ParameterList,
accessorList: syntax.AccessorList,
expressionBody: syntax.ExpressionBody,
semicolonToken: syntax.SemicolonToken);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/Core/Portable/FindUsages/IFindUsagesContext.cs | // Licensed to the .NET Foundation under one or more 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.Shared.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
internal interface IFindUsagesContext
{
/// <summary>
/// Used for clients that are finding usages to push information about how far along they
/// are in their search.
/// </summary>
IStreamingProgressTracker ProgressTracker { get; }
/// <summary>
/// Report a message to be displayed to the user.
/// </summary>
ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken);
/// <summary>
/// Set the title of the window that results are displayed in.
/// </summary>
ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken);
ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken);
ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
internal interface IFindUsagesContext
{
/// <summary>
/// Used for clients that are finding usages to push information about how far along they
/// are in their search.
/// </summary>
IStreamingProgressTracker ProgressTracker { get; }
/// <summary>
/// Report a message to be displayed to the user.
/// </summary>
ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken);
/// <summary>
/// Set the title of the window that results are displayed in.
/// </summary>
ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken);
ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken);
ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Portable/Parser/Blender.Cursor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal partial struct Blender
{
/// <summary>
/// THe cursor represents a location in the tree that we can move around to indicate where
/// we are in the original tree as we're incrementally parsing. When it is at a node or
/// token, it can either move forward to that entity's next sibling. It can also move down
/// to a node's first child or first token.
///
/// Once the cursor hits the end of file, it's done. Note: the cursor will skip any other
/// zero length nodes in the tree.
/// </summary>
private struct Cursor
{
public readonly SyntaxNodeOrToken CurrentNodeOrToken;
private readonly int _indexInParent;
private Cursor(SyntaxNodeOrToken node, int indexInParent)
{
this.CurrentNodeOrToken = node;
_indexInParent = indexInParent;
}
public static Cursor FromRoot(CSharp.CSharpSyntaxNode node)
{
return new Cursor(node, indexInParent: 0);
}
public bool IsFinished
{
get
{
return
this.CurrentNodeOrToken.Kind() == SyntaxKind.None ||
this.CurrentNodeOrToken.Kind() == SyntaxKind.EndOfFileToken;
}
}
private static bool IsNonZeroWidthOrIsEndOfFile(SyntaxNodeOrToken token)
{
return token.Kind() == SyntaxKind.EndOfFileToken || token.FullWidth != 0;
}
public Cursor MoveToNextSibling()
{
if (this.CurrentNodeOrToken.Parent != null)
{
// First, look to the nodes to the right of this one in our parent's child list
// to get the next sibling.
var siblings = this.CurrentNodeOrToken.Parent.ChildNodesAndTokens();
for (int i = _indexInParent + 1, n = siblings.Count; i < n; i++)
{
var sibling = siblings[i];
if (IsNonZeroWidthOrIsEndOfFile(sibling))
{
return new Cursor(sibling, i);
}
}
// We're at the end of this sibling chain. Walk up to the parent and see who is
// the next sibling of that.
return MoveToParent().MoveToNextSibling();
}
return default(Cursor);
}
private Cursor MoveToParent()
{
var parent = this.CurrentNodeOrToken.Parent;
var index = IndexOfNodeInParent(parent);
return new Cursor(parent, index);
}
private static int IndexOfNodeInParent(SyntaxNode node)
{
if (node.Parent == null)
{
return 0;
}
var children = node.Parent.ChildNodesAndTokens();
var index = SyntaxNodeOrToken.GetFirstChildIndexSpanningPosition(children, ((CSharp.CSharpSyntaxNode)node).Position);
for (int i = index, n = children.Count; i < n; i++)
{
var child = children[i];
if (child == node)
{
return i;
}
}
throw ExceptionUtilities.Unreachable;
}
public Cursor MoveToFirstChild()
{
Debug.Assert(this.CurrentNodeOrToken.IsNode);
// Just try to get the first node directly. This is faster than getting the list of
// child nodes and tokens (which forces all children to be enumerated for the sake
// of counting. It should always be safe to index the 0th element of a node. But
// just to make sure that this is not a problem, we verify that the slot count of the
// node is greater than 0.
var node = CurrentNodeOrToken.AsNode();
// Interpolated strings cannot be scanned or parsed incrementally. Instead they must be
// turned into and then reparsed from the single InterpolatedStringToken. We therefore
// do not break interpolated string nodes down into their constituent tokens, but
// instead replace the whole parsed interpolated string expression with its pre-parsed
// interpolated string token.
if (node.Kind() == SyntaxKind.InterpolatedStringExpression)
{
var greenToken = Lexer.RescanInterpolatedString((InterpolatedStringExpressionSyntax)node.Green);
var redToken = new CodeAnalysis.SyntaxToken(node.Parent, greenToken, node.Position, _indexInParent);
return new Cursor(redToken, _indexInParent);
}
if (node.SlotCount > 0)
{
var child = Microsoft.CodeAnalysis.ChildSyntaxList.ItemInternal(node, 0);
if (IsNonZeroWidthOrIsEndOfFile(child))
{
return new Cursor(child, 0);
}
}
// Fallback to enumerating all children.
int index = 0;
foreach (var child in this.CurrentNodeOrToken.ChildNodesAndTokens())
{
if (IsNonZeroWidthOrIsEndOfFile(child))
{
return new Cursor(child, index);
}
index++;
}
return new Cursor();
}
public Cursor MoveToFirstToken()
{
var cursor = this;
if (!cursor.IsFinished)
{
for (var node = cursor.CurrentNodeOrToken; node.Kind() != SyntaxKind.None && !SyntaxFacts.IsAnyToken(node.Kind()); node = cursor.CurrentNodeOrToken)
{
cursor = cursor.MoveToFirstChild();
}
}
return cursor;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal partial struct Blender
{
/// <summary>
/// THe cursor represents a location in the tree that we can move around to indicate where
/// we are in the original tree as we're incrementally parsing. When it is at a node or
/// token, it can either move forward to that entity's next sibling. It can also move down
/// to a node's first child or first token.
///
/// Once the cursor hits the end of file, it's done. Note: the cursor will skip any other
/// zero length nodes in the tree.
/// </summary>
private struct Cursor
{
public readonly SyntaxNodeOrToken CurrentNodeOrToken;
private readonly int _indexInParent;
private Cursor(SyntaxNodeOrToken node, int indexInParent)
{
this.CurrentNodeOrToken = node;
_indexInParent = indexInParent;
}
public static Cursor FromRoot(CSharp.CSharpSyntaxNode node)
{
return new Cursor(node, indexInParent: 0);
}
public bool IsFinished
{
get
{
return
this.CurrentNodeOrToken.Kind() == SyntaxKind.None ||
this.CurrentNodeOrToken.Kind() == SyntaxKind.EndOfFileToken;
}
}
private static bool IsNonZeroWidthOrIsEndOfFile(SyntaxNodeOrToken token)
{
return token.Kind() == SyntaxKind.EndOfFileToken || token.FullWidth != 0;
}
public Cursor MoveToNextSibling()
{
if (this.CurrentNodeOrToken.Parent != null)
{
// First, look to the nodes to the right of this one in our parent's child list
// to get the next sibling.
var siblings = this.CurrentNodeOrToken.Parent.ChildNodesAndTokens();
for (int i = _indexInParent + 1, n = siblings.Count; i < n; i++)
{
var sibling = siblings[i];
if (IsNonZeroWidthOrIsEndOfFile(sibling))
{
return new Cursor(sibling, i);
}
}
// We're at the end of this sibling chain. Walk up to the parent and see who is
// the next sibling of that.
return MoveToParent().MoveToNextSibling();
}
return default(Cursor);
}
private Cursor MoveToParent()
{
var parent = this.CurrentNodeOrToken.Parent;
var index = IndexOfNodeInParent(parent);
return new Cursor(parent, index);
}
private static int IndexOfNodeInParent(SyntaxNode node)
{
if (node.Parent == null)
{
return 0;
}
var children = node.Parent.ChildNodesAndTokens();
var index = SyntaxNodeOrToken.GetFirstChildIndexSpanningPosition(children, ((CSharp.CSharpSyntaxNode)node).Position);
for (int i = index, n = children.Count; i < n; i++)
{
var child = children[i];
if (child == node)
{
return i;
}
}
throw ExceptionUtilities.Unreachable;
}
public Cursor MoveToFirstChild()
{
Debug.Assert(this.CurrentNodeOrToken.IsNode);
// Just try to get the first node directly. This is faster than getting the list of
// child nodes and tokens (which forces all children to be enumerated for the sake
// of counting. It should always be safe to index the 0th element of a node. But
// just to make sure that this is not a problem, we verify that the slot count of the
// node is greater than 0.
var node = CurrentNodeOrToken.AsNode();
// Interpolated strings cannot be scanned or parsed incrementally. Instead they must be
// turned into and then reparsed from the single InterpolatedStringToken. We therefore
// do not break interpolated string nodes down into their constituent tokens, but
// instead replace the whole parsed interpolated string expression with its pre-parsed
// interpolated string token.
if (node.Kind() == SyntaxKind.InterpolatedStringExpression)
{
var greenToken = Lexer.RescanInterpolatedString((InterpolatedStringExpressionSyntax)node.Green);
var redToken = new CodeAnalysis.SyntaxToken(node.Parent, greenToken, node.Position, _indexInParent);
return new Cursor(redToken, _indexInParent);
}
if (node.SlotCount > 0)
{
var child = Microsoft.CodeAnalysis.ChildSyntaxList.ItemInternal(node, 0);
if (IsNonZeroWidthOrIsEndOfFile(child))
{
return new Cursor(child, 0);
}
}
// Fallback to enumerating all children.
int index = 0;
foreach (var child in this.CurrentNodeOrToken.ChildNodesAndTokens())
{
if (IsNonZeroWidthOrIsEndOfFile(child))
{
return new Cursor(child, index);
}
index++;
}
return new Cursor();
}
public Cursor MoveToFirstToken()
{
var cursor = this;
if (!cursor.IsFinished)
{
for (var node = cursor.CurrentNodeOrToken; node.Kind() != SyntaxKind.None && !SyntaxFacts.IsAnyToken(node.Kind()); node = cursor.CurrentNodeOrToken)
{
cursor = cursor.MoveToFirstChild();
}
}
return cursor;
}
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/CoreTest/SolutionTests/SolutionInfoTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class SolutionInfoTests
{
[Fact]
public void Create_Errors()
{
var solutionId = SolutionId.CreateNewId();
var version = VersionStamp.Default;
var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#");
Assert.Throws<ArgumentNullException>(() => SolutionInfo.Create(null, version));
Assert.Throws<ArgumentNullException>(() => SolutionInfo.Create(solutionId, version, projects: new[] { projectInfo, null }));
}
[Fact]
public void Create_Projects()
{
var solutionId = SolutionId.CreateNewId();
var version = VersionStamp.Default;
var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#");
var info1 = SolutionInfo.Create(solutionId, version, projects: new[] { projectInfo });
Assert.Same(projectInfo, ((ImmutableArray<ProjectInfo>)info1.Projects).Single());
var info2 = SolutionInfo.Create(solutionId, version);
Assert.True(((ImmutableArray<ProjectInfo>)info2.Projects).IsEmpty);
var info3 = SolutionInfo.Create(solutionId, version, projects: new ProjectInfo[0]);
Assert.True(((ImmutableArray<ProjectInfo>)info3.Projects).IsEmpty);
var info4 = SolutionInfo.Create(solutionId, version, projects: ImmutableArray<ProjectInfo>.Empty);
Assert.True(((ImmutableArray<ProjectInfo>)info4.Projects).IsEmpty);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("path")]
public void Create_FilePath(string path)
{
var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, filePath: path);
Assert.Equal(path, info.FilePath);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class SolutionInfoTests
{
[Fact]
public void Create_Errors()
{
var solutionId = SolutionId.CreateNewId();
var version = VersionStamp.Default;
var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#");
Assert.Throws<ArgumentNullException>(() => SolutionInfo.Create(null, version));
Assert.Throws<ArgumentNullException>(() => SolutionInfo.Create(solutionId, version, projects: new[] { projectInfo, null }));
}
[Fact]
public void Create_Projects()
{
var solutionId = SolutionId.CreateNewId();
var version = VersionStamp.Default;
var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#");
var info1 = SolutionInfo.Create(solutionId, version, projects: new[] { projectInfo });
Assert.Same(projectInfo, ((ImmutableArray<ProjectInfo>)info1.Projects).Single());
var info2 = SolutionInfo.Create(solutionId, version);
Assert.True(((ImmutableArray<ProjectInfo>)info2.Projects).IsEmpty);
var info3 = SolutionInfo.Create(solutionId, version, projects: new ProjectInfo[0]);
Assert.True(((ImmutableArray<ProjectInfo>)info3.Projects).IsEmpty);
var info4 = SolutionInfo.Create(solutionId, version, projects: ImmutableArray<ProjectInfo>.Empty);
Assert.True(((ImmutableArray<ProjectInfo>)info4.Projects).IsEmpty);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("path")]
public void Create_FilePath(string path)
{
var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, filePath: path);
Assert.Equal(path, info.FilePath);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/Core/CodeAnalysisTest/DefaultAnalyzerAssemblyLoaderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.UnitTests
{
[CollectionDefinition(Name)]
public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture>
{
public const string Name = nameof(AssemblyLoadTestFixtureCollection);
private AssemblyLoadTestFixtureCollection() { }
}
[Collection(AssemblyLoadTestFixtureCollection.Name)]
public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase
{
private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel);
private readonly ITestOutputHelper _output;
private readonly AssemblyLoadTestFixture _testFixture;
public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture)
{
_output = output;
_testFixture = testFixture;
}
[Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")]
public void LoadWithDependency()
{
var analyzerDependencyFile = _testFixture.AnalyzerDependency;
var analyzerMainFile = _testFixture.AnalyzerWithDependency;
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(analyzerDependencyFile.Path);
var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader);
analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);
var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader);
analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);
var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages();
Assert.Equal(1, analyzers.Length);
Assert.Equal("TestAnalyzer", analyzers[0].ToString());
Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length);
Assert.NotNull(analyzerDependencyReference.GetAssembly());
}
[Fact]
public void AddDependencyLocationThrowsOnNull()
{
var loader = new DefaultAnalyzerAssemblyLoader();
Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null));
Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a"));
}
[Fact]
public void ThrowsForMissingFile()
{
var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll");
var loader = new DefaultAnalyzerAssemblyLoader();
Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path));
}
[Fact]
public void BasicLoad()
{
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Alpha.Path);
Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);
Assert.NotNull(alpha);
}
[Fact]
public void AssemblyLoading()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Alpha.Path);
loader.AddDependencyLocation(_testFixture.Beta.Path);
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);
var a = alpha.CreateInstance("Alpha.A")!;
a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" });
Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);
var b = beta.CreateInstance("Beta.B")!;
b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" });
var expected = @"Delta: Gamma: Alpha: Test A
Delta: Gamma: Beta: Test B
";
var actual = sb.ToString();
Assert.Equal(expected, actual);
}
[ConditionalFact(typeof(CoreClrOnly))]
public void AssemblyLoading_AssemblyLocationNotAdded()
{
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path));
}
[ConditionalFact(typeof(CoreClrOnly))]
public void AssemblyLoading_DependencyLocationNotAdded()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
// We don't pass Alpha's path to AddDependencyLocation here, and therefore expect
// calling Beta.B.Write to fail.
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Beta.Path);
Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);
var b = beta.CreateInstance("Beta.B")!;
var writeMethod = b.GetType().GetMethod("Write")!;
var exception = Assert.Throws<TargetInvocationException>(
() => writeMethod.Invoke(b, new object[] { sb, "Test B" }));
Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException);
var actual = sb.ToString();
Assert.Equal(@"", actual);
}
[Fact]
public void AssemblyLoading_MultipleVersions()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
loader.AddDependencyLocation(_testFixture.Epsilon.Path);
loader.AddDependencyLocation(_testFixture.Delta2.Path);
Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);
var g = gamma.CreateInstance("Gamma.G")!;
g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" });
Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);
var e = epsilon.CreateInstance("Epsilon.E")!;
e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" });
#if NETCOREAPP
var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);
Assert.Equal(2, alcs.Length);
Assert.Equal(new[] {
("Delta", "1.0.0.0", _testFixture.Delta1.Path),
("Gamma", "0.0.0.0", _testFixture.Gamma.Path)
}, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
Assert.Equal(new[] {
("Delta", "2.0.0.0", _testFixture.Delta2.Path),
("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)
}, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
#endif
var actual = sb.ToString();
if (ExecutionConditionUtil.IsCoreClr)
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta.2: Epsilon: Test E
",
actual);
}
else
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta: Epsilon: Test E
",
actual);
}
}
[Fact]
public void AssemblyLoading_MultipleVersions_MultipleLoaders()
{
StringBuilder sb = new StringBuilder();
var loader1 = new DefaultAnalyzerAssemblyLoader();
loader1.AddDependencyLocation(_testFixture.Gamma.Path);
loader1.AddDependencyLocation(_testFixture.Delta1.Path);
var loader2 = new DefaultAnalyzerAssemblyLoader();
loader2.AddDependencyLocation(_testFixture.Epsilon.Path);
loader2.AddDependencyLocation(_testFixture.Delta2.Path);
Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path);
var g = gamma.CreateInstance("Gamma.G")!;
g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" });
Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path);
var e = epsilon.CreateInstance("Epsilon.E")!;
e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" });
#if NETCOREAPP
var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1);
Assert.Equal(1, alcs1.Length);
Assert.Equal(new[] {
("Delta", "1.0.0.0", _testFixture.Delta1.Path),
("Gamma", "0.0.0.0", _testFixture.Gamma.Path)
}, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2);
Assert.Equal(1, alcs2.Length);
Assert.Equal(new[] {
("Delta", "2.0.0.0", _testFixture.Delta2.Path),
("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)
}, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
#endif
var actual = sb.ToString();
if (ExecutionConditionUtil.IsCoreClr)
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta.2: Epsilon: Test E
",
actual);
}
else
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta: Epsilon: Test E
",
actual);
}
}
[Fact]
public void AssemblyLoading_MultipleVersions_MissingVersion()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
loader.AddDependencyLocation(_testFixture.Epsilon.Path);
Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);
var g = gamma.CreateInstance("Gamma.G")!;
g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" });
Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);
var e = epsilon.CreateInstance("Epsilon.E")!;
var eWrite = e.GetType().GetMethod("Write")!;
var actual = sb.ToString();
if (ExecutionConditionUtil.IsCoreClr)
{
var exception = Assert.Throws<TargetInvocationException>(() => eWrite.Invoke(e, new object[] { sb, "Test E" }));
Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException);
}
else
{
eWrite.Invoke(e, new object[] { sb, "Test E" });
Assert.Equal(
@"Delta: Gamma: Test G
",
actual);
}
}
[Fact]
public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);
loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);
Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);
var analyzer = analyzerAssembly.CreateInstance("Analyzer")!;
if (ExecutionConditionUtil.IsCoreClr)
{
var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }));
Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}""");
}
else
{
analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb });
Assert.Equal("42", sb.ToString());
}
}
[Fact]
public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);
loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);
Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);
var analyzer = analyzerAssembly.CreateInstance("Analyzer")!;
analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb });
Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString());
}
[ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))]
public void AssemblyLoading_NativeDependency()
{
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path);
Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path);
var analyzer = analyzerAssembly.CreateInstance("Class1")!;
var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path });
Assert.Equal(0, Marshal.GetLastWin32Error());
Assert.Equal(FileAttributes.Archive, (FileAttributes)result!);
}
#if NETCOREAPP
[Fact]
public void VerifyCompilerAssemblySimpleNames()
{
var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly;
var caReferences = caAssembly.GetReferencedAssemblies();
var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance();
allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException());
foreach (var reference in caReferences)
{
allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException());
}
var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly;
allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException());
var csReferences = csAssembly.GetReferencedAssemblies();
foreach (var reference in csReferences)
{
var name = reference.Name ?? throw new InvalidOperationException();
if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))
{
allReferenceSimpleNames.Add(name);
}
}
var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly;
var vbReferences = vbAssembly.GetReferencedAssemblies();
allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException());
foreach (var reference in vbReferences)
{
var name = reference.Name ?? throw new InvalidOperationException();
if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))
{
allReferenceSimpleNames.Add(name);
}
}
if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames))
{
allReferenceSimpleNames.Sort();
var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}"""));
_output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames =");
_output.WriteLine(" ImmutableHashSet.Create(");
_output.WriteLine(" StringComparer.OrdinalIgnoreCase,");
_output.WriteLine($" {allNames});");
allReferenceSimpleNames.Free();
Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it.");
}
else
{
allReferenceSimpleNames.Free();
}
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.UnitTests
{
[CollectionDefinition(Name)]
public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture>
{
public const string Name = nameof(AssemblyLoadTestFixtureCollection);
private AssemblyLoadTestFixtureCollection() { }
}
[Collection(AssemblyLoadTestFixtureCollection.Name)]
public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase
{
private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel);
private readonly ITestOutputHelper _output;
private readonly AssemblyLoadTestFixture _testFixture;
public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture)
{
_output = output;
_testFixture = testFixture;
}
[Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")]
public void LoadWithDependency()
{
var analyzerDependencyFile = _testFixture.AnalyzerDependency;
var analyzerMainFile = _testFixture.AnalyzerWithDependency;
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(analyzerDependencyFile.Path);
var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader);
analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);
var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader);
analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);
var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages();
Assert.Equal(1, analyzers.Length);
Assert.Equal("TestAnalyzer", analyzers[0].ToString());
Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length);
Assert.NotNull(analyzerDependencyReference.GetAssembly());
}
[Fact]
public void AddDependencyLocationThrowsOnNull()
{
var loader = new DefaultAnalyzerAssemblyLoader();
Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null));
Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a"));
}
[Fact]
public void ThrowsForMissingFile()
{
var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll");
var loader = new DefaultAnalyzerAssemblyLoader();
Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path));
}
[Fact]
public void BasicLoad()
{
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Alpha.Path);
Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);
Assert.NotNull(alpha);
}
[Fact]
public void AssemblyLoading()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Alpha.Path);
loader.AddDependencyLocation(_testFixture.Beta.Path);
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);
var a = alpha.CreateInstance("Alpha.A")!;
a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" });
Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);
var b = beta.CreateInstance("Beta.B")!;
b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" });
var expected = @"Delta: Gamma: Alpha: Test A
Delta: Gamma: Beta: Test B
";
var actual = sb.ToString();
Assert.Equal(expected, actual);
}
[ConditionalFact(typeof(CoreClrOnly))]
public void AssemblyLoading_AssemblyLocationNotAdded()
{
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path));
}
[ConditionalFact(typeof(CoreClrOnly))]
public void AssemblyLoading_DependencyLocationNotAdded()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
// We don't pass Alpha's path to AddDependencyLocation here, and therefore expect
// calling Beta.B.Write to fail.
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Beta.Path);
Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);
var b = beta.CreateInstance("Beta.B")!;
var writeMethod = b.GetType().GetMethod("Write")!;
var exception = Assert.Throws<TargetInvocationException>(
() => writeMethod.Invoke(b, new object[] { sb, "Test B" }));
Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException);
var actual = sb.ToString();
Assert.Equal(@"", actual);
}
[Fact]
public void AssemblyLoading_MultipleVersions()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
loader.AddDependencyLocation(_testFixture.Epsilon.Path);
loader.AddDependencyLocation(_testFixture.Delta2.Path);
Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);
var g = gamma.CreateInstance("Gamma.G")!;
g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" });
Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);
var e = epsilon.CreateInstance("Epsilon.E")!;
e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" });
#if NETCOREAPP
var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);
Assert.Equal(2, alcs.Length);
Assert.Equal(new[] {
("Delta", "1.0.0.0", _testFixture.Delta1.Path),
("Gamma", "0.0.0.0", _testFixture.Gamma.Path)
}, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
Assert.Equal(new[] {
("Delta", "2.0.0.0", _testFixture.Delta2.Path),
("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)
}, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
#endif
var actual = sb.ToString();
if (ExecutionConditionUtil.IsCoreClr)
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta.2: Epsilon: Test E
",
actual);
}
else
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta: Epsilon: Test E
",
actual);
}
}
[Fact]
public void AssemblyLoading_MultipleVersions_MultipleLoaders()
{
StringBuilder sb = new StringBuilder();
var loader1 = new DefaultAnalyzerAssemblyLoader();
loader1.AddDependencyLocation(_testFixture.Gamma.Path);
loader1.AddDependencyLocation(_testFixture.Delta1.Path);
var loader2 = new DefaultAnalyzerAssemblyLoader();
loader2.AddDependencyLocation(_testFixture.Epsilon.Path);
loader2.AddDependencyLocation(_testFixture.Delta2.Path);
Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path);
var g = gamma.CreateInstance("Gamma.G")!;
g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" });
Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path);
var e = epsilon.CreateInstance("Epsilon.E")!;
e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" });
#if NETCOREAPP
var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1);
Assert.Equal(1, alcs1.Length);
Assert.Equal(new[] {
("Delta", "1.0.0.0", _testFixture.Delta1.Path),
("Gamma", "0.0.0.0", _testFixture.Gamma.Path)
}, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2);
Assert.Equal(1, alcs2.Length);
Assert.Equal(new[] {
("Delta", "2.0.0.0", _testFixture.Delta2.Path),
("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)
}, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());
#endif
var actual = sb.ToString();
if (ExecutionConditionUtil.IsCoreClr)
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta.2: Epsilon: Test E
",
actual);
}
else
{
Assert.Equal(
@"Delta: Gamma: Test G
Delta: Epsilon: Test E
",
actual);
}
}
[Fact]
public void AssemblyLoading_MultipleVersions_MissingVersion()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.Gamma.Path);
loader.AddDependencyLocation(_testFixture.Delta1.Path);
loader.AddDependencyLocation(_testFixture.Epsilon.Path);
Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);
var g = gamma.CreateInstance("Gamma.G")!;
g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" });
Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);
var e = epsilon.CreateInstance("Epsilon.E")!;
var eWrite = e.GetType().GetMethod("Write")!;
var actual = sb.ToString();
if (ExecutionConditionUtil.IsCoreClr)
{
var exception = Assert.Throws<TargetInvocationException>(() => eWrite.Invoke(e, new object[] { sb, "Test E" }));
Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException);
}
else
{
eWrite.Invoke(e, new object[] { sb, "Test E" });
Assert.Equal(
@"Delta: Gamma: Test G
",
actual);
}
}
[Fact]
public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);
loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);
Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);
var analyzer = analyzerAssembly.CreateInstance("Analyzer")!;
if (ExecutionConditionUtil.IsCoreClr)
{
var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }));
Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}""");
}
else
{
analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb });
Assert.Equal("42", sb.ToString());
}
}
[Fact]
public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02()
{
StringBuilder sb = new StringBuilder();
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);
loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);
Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);
var analyzer = analyzerAssembly.CreateInstance("Analyzer")!;
analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb });
Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString());
}
[ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))]
public void AssemblyLoading_NativeDependency()
{
var loader = new DefaultAnalyzerAssemblyLoader();
loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path);
Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path);
var analyzer = analyzerAssembly.CreateInstance("Class1")!;
var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path });
Assert.Equal(0, Marshal.GetLastWin32Error());
Assert.Equal(FileAttributes.Archive, (FileAttributes)result!);
}
#if NETCOREAPP
[Fact]
public void VerifyCompilerAssemblySimpleNames()
{
var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly;
var caReferences = caAssembly.GetReferencedAssemblies();
var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance();
allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException());
foreach (var reference in caReferences)
{
allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException());
}
var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly;
allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException());
var csReferences = csAssembly.GetReferencedAssemblies();
foreach (var reference in csReferences)
{
var name = reference.Name ?? throw new InvalidOperationException();
if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))
{
allReferenceSimpleNames.Add(name);
}
}
var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly;
var vbReferences = vbAssembly.GetReferencedAssemblies();
allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException());
foreach (var reference in vbReferences)
{
var name = reference.Name ?? throw new InvalidOperationException();
if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))
{
allReferenceSimpleNames.Add(name);
}
}
if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames))
{
allReferenceSimpleNames.Sort();
var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}"""));
_output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames =");
_output.WriteLine(" ImmutableHashSet.Create(");
_output.WriteLine(" StringComparer.OrdinalIgnoreCase,");
_output.WriteLine($" {allNames});");
allReferenceSimpleNames.Free();
Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it.");
}
else
{
allReferenceSimpleNames.Free();
}
}
#endif
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/Core/Portable/InternalLanguageNames.cs | // Licensed to the .NET Foundation under one or more 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
{
/// <summary>
/// A class that provides constants for internal partner language names.
/// </summary>
internal static class InternalLanguageNames
{
public const string TypeScript = "TypeScript";
}
}
| // Licensed to the .NET Foundation under one or more 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
{
/// <summary>
/// A class that provides constants for internal partner language names.
/// </summary>
internal static class InternalLanguageNames
{
public const string TypeScript = "TypeScript";
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/Text/Shared/Extensions/ITextSnapshotLineExtensions.cs | // Licensed to the .NET Foundation under one or more 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.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text.Shared.Extensions
{
internal static class ITextSnapshotLineExtensions
{
/// <summary>
/// Returns the first non-whitespace position on the given line, or null if
/// the line is empty or contains only whitespace.
/// </summary>
public static int? GetFirstNonWhitespacePosition(this ITextSnapshotLine line)
{
Contract.ThrowIfNull(line);
var text = line.GetText();
for (var i = 0; i < text.Length; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return line.Start + i;
}
}
return null;
}
/// <summary>
/// Returns the first non-whitespace position on the given line as an offset
/// from the start of the line, or null if the line is empty or contains only
/// whitespace.
/// </summary>
public static int? GetFirstNonWhitespaceOffset(this ITextSnapshotLine line)
{
Contract.ThrowIfNull(line);
var text = line.GetText();
for (var i = 0; i < text.Length; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return i;
}
}
return null;
}
/// <summary>
/// Returns the last non-whitespace position on the given line, or null if
/// the line is empty or contains only whitespace.
/// </summary>
public static int? GetLastNonWhitespacePosition(this ITextSnapshotLine line)
=> line.AsTextLine().GetLastNonWhitespacePosition();
/// <summary>
/// Determines whether the specified line is empty or contains whitespace only.
/// </summary>
public static bool IsEmptyOrWhitespace(this ITextSnapshotLine line, int startIndex = 0, int endIndex = -1)
{
Contract.ThrowIfNull(line, "line");
Contract.ThrowIfFalse(startIndex >= 0);
var text = line.GetText();
if (endIndex == -1)
{
endIndex = text.Length;
}
for (var i = startIndex; i < endIndex; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return false;
}
}
return true;
}
public static ITextSnapshotLine? GetPreviousMatchingLine(this ITextSnapshotLine line, Func<ITextSnapshotLine, bool> predicate)
{
Contract.ThrowIfNull(line, @"line");
Contract.ThrowIfNull(predicate, @"tree");
if (line.LineNumber <= 0)
{
return null;
}
var snapshot = line.Snapshot;
for (var lineNumber = line.LineNumber - 1; lineNumber >= 0; lineNumber--)
{
var currentLine = snapshot.GetLineFromLineNumber(lineNumber);
if (!predicate(currentLine))
{
continue;
}
return currentLine;
}
return null;
}
public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this ITextSnapshotLine line, IEditorOptions editorOptions)
=> line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(editorOptions.GetTabSize());
public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this ITextSnapshotLine line, int tabSize)
=> line.GetText().GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(tabSize);
public static int GetColumnFromLineOffset(this ITextSnapshotLine line, int lineOffset, IEditorOptions editorOptions)
=> line.GetText().GetColumnFromLineOffset(lineOffset, editorOptions.GetTabSize());
public static int GetLineOffsetFromColumn(this ITextSnapshotLine line, int column, IEditorOptions editorOptions)
=> line.GetText().GetLineOffsetFromColumn(column, editorOptions.GetTabSize());
/// <summary>
/// Checks if the given line at the given snapshot index starts with the provided value.
/// </summary>
public static bool StartsWith(this ITextSnapshotLine line, int index, string value, bool ignoreCase)
{
var snapshot = line.Snapshot;
if (index + value.Length > snapshot.Length)
return false;
for (var i = 0; i < value.Length; i++)
{
var snapshotIndex = index + i;
var actualCharacter = snapshot[snapshotIndex];
var expectedCharacter = value[i];
if (ignoreCase)
{
actualCharacter = char.ToLowerInvariant(actualCharacter);
expectedCharacter = char.ToLowerInvariant(expectedCharacter);
}
if (actualCharacter != expectedCharacter)
return false;
}
return true;
}
public static bool Contains(this ITextSnapshotLine line, int index, string value, bool ignoreCase)
{
var snapshot = line.Snapshot;
for (var i = index; i < line.End; i++)
{
if (i + value.Length > snapshot.Length)
return false;
if (line.StartsWith(i, value, ignoreCase))
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;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text.Shared.Extensions
{
internal static class ITextSnapshotLineExtensions
{
/// <summary>
/// Returns the first non-whitespace position on the given line, or null if
/// the line is empty or contains only whitespace.
/// </summary>
public static int? GetFirstNonWhitespacePosition(this ITextSnapshotLine line)
{
Contract.ThrowIfNull(line);
var text = line.GetText();
for (var i = 0; i < text.Length; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return line.Start + i;
}
}
return null;
}
/// <summary>
/// Returns the first non-whitespace position on the given line as an offset
/// from the start of the line, or null if the line is empty or contains only
/// whitespace.
/// </summary>
public static int? GetFirstNonWhitespaceOffset(this ITextSnapshotLine line)
{
Contract.ThrowIfNull(line);
var text = line.GetText();
for (var i = 0; i < text.Length; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return i;
}
}
return null;
}
/// <summary>
/// Returns the last non-whitespace position on the given line, or null if
/// the line is empty or contains only whitespace.
/// </summary>
public static int? GetLastNonWhitespacePosition(this ITextSnapshotLine line)
=> line.AsTextLine().GetLastNonWhitespacePosition();
/// <summary>
/// Determines whether the specified line is empty or contains whitespace only.
/// </summary>
public static bool IsEmptyOrWhitespace(this ITextSnapshotLine line, int startIndex = 0, int endIndex = -1)
{
Contract.ThrowIfNull(line, "line");
Contract.ThrowIfFalse(startIndex >= 0);
var text = line.GetText();
if (endIndex == -1)
{
endIndex = text.Length;
}
for (var i = startIndex; i < endIndex; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return false;
}
}
return true;
}
public static ITextSnapshotLine? GetPreviousMatchingLine(this ITextSnapshotLine line, Func<ITextSnapshotLine, bool> predicate)
{
Contract.ThrowIfNull(line, @"line");
Contract.ThrowIfNull(predicate, @"tree");
if (line.LineNumber <= 0)
{
return null;
}
var snapshot = line.Snapshot;
for (var lineNumber = line.LineNumber - 1; lineNumber >= 0; lineNumber--)
{
var currentLine = snapshot.GetLineFromLineNumber(lineNumber);
if (!predicate(currentLine))
{
continue;
}
return currentLine;
}
return null;
}
public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this ITextSnapshotLine line, IEditorOptions editorOptions)
=> line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(editorOptions.GetTabSize());
public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this ITextSnapshotLine line, int tabSize)
=> line.GetText().GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(tabSize);
public static int GetColumnFromLineOffset(this ITextSnapshotLine line, int lineOffset, IEditorOptions editorOptions)
=> line.GetText().GetColumnFromLineOffset(lineOffset, editorOptions.GetTabSize());
public static int GetLineOffsetFromColumn(this ITextSnapshotLine line, int column, IEditorOptions editorOptions)
=> line.GetText().GetLineOffsetFromColumn(column, editorOptions.GetTabSize());
/// <summary>
/// Checks if the given line at the given snapshot index starts with the provided value.
/// </summary>
public static bool StartsWith(this ITextSnapshotLine line, int index, string value, bool ignoreCase)
{
var snapshot = line.Snapshot;
if (index + value.Length > snapshot.Length)
return false;
for (var i = 0; i < value.Length; i++)
{
var snapshotIndex = index + i;
var actualCharacter = snapshot[snapshotIndex];
var expectedCharacter = value[i];
if (ignoreCase)
{
actualCharacter = char.ToLowerInvariant(actualCharacter);
expectedCharacter = char.ToLowerInvariant(expectedCharacter);
}
if (actualCharacter != expectedCharacter)
return false;
}
return true;
}
public static bool Contains(this ITextSnapshotLine line, int index, string value, bool ignoreCase)
{
var snapshot = line.Snapshot;
for (var i = index; i < line.End; i++)
{
if (i + value.Length > snapshot.Length)
return false;
if (line.StartsWith(i, value, ignoreCase))
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/Core/Portable/Diagnostics/InternalDiagnosticsOptionsProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Diagnostics
{
[ExportOptionProvider, Shared]
internal class InternalDiagnosticsOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InternalDiagnosticsOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
InternalDiagnosticsOptions.PreferLiveErrorsOnOpenedFiles,
InternalDiagnosticsOptions.PreferBuildErrorsOverLiveErrors);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Diagnostics
{
[ExportOptionProvider, Shared]
internal class InternalDiagnosticsOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InternalDiagnosticsOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
InternalDiagnosticsOptions.PreferLiveErrorsOnOpenedFiles,
InternalDiagnosticsOptions.PreferBuildErrorsOverLiveErrors);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/Core/Portable/ReferenceManager/AssemblyReferenceBinding.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
{
/// <summary>
/// Result of binding an AssemblyRef to an AssemblyDef.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal readonly struct AssemblyReferenceBinding
{
private readonly AssemblyIdentity? _referenceIdentity;
private readonly int _definitionIndex;
private readonly int _versionDifference;
/// <summary>
/// Failed binding.
/// </summary>
public AssemblyReferenceBinding(AssemblyIdentity referenceIdentity)
{
Debug.Assert(referenceIdentity != null);
_referenceIdentity = referenceIdentity;
_definitionIndex = -1;
_versionDifference = 0;
}
/// <summary>
/// Successful binding.
/// </summary>
public AssemblyReferenceBinding(AssemblyIdentity referenceIdentity, int definitionIndex, int versionDifference = 0)
{
Debug.Assert(referenceIdentity != null);
Debug.Assert(definitionIndex >= 0);
Debug.Assert(versionDifference >= -1 && versionDifference <= +1);
_referenceIdentity = referenceIdentity;
_definitionIndex = definitionIndex;
_versionDifference = versionDifference;
}
/// <summary>
/// Returns true if the reference was matched with the identity of the assembly being built.
/// </summary>
internal bool BoundToAssemblyBeingBuilt
{
get { return _definitionIndex == 0; }
}
/// <summary>
/// True if the definition index is available (reference was successfully matched with the definition).
/// </summary>
internal bool IsBound
{
get
{
return _definitionIndex >= 0;
}
}
/// <summary>
/// 0 if the reference is equivalent to the definition.
/// -1 if version of the matched definition is lower than version of the reference, but the reference otherwise matches the definition.
/// +1 if version of the matched definition is higher than version of the reference, but the reference otherwise matches the definition.
///
/// Undefined unless <see cref="IsBound"/> is true.
/// </summary>
internal int VersionDifference
{
get
{
Debug.Assert(IsBound);
return _versionDifference;
}
}
/// <summary>
/// Index into assembly definition list.
/// Undefined unless <see cref="IsBound"/> is true.
/// </summary>
internal int DefinitionIndex
{
get
{
Debug.Assert(IsBound);
return _definitionIndex;
}
}
internal AssemblyIdentity? ReferenceIdentity
{
get
{
return _referenceIdentity;
}
}
private string GetDebuggerDisplay()
{
var displayName = ReferenceIdentity?.GetDisplayName() ?? "";
return IsBound ? displayName + " -> #" + DefinitionIndex + (VersionDifference != 0 ? " VersionDiff=" + VersionDifference : "") : "unbound";
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
{
/// <summary>
/// Result of binding an AssemblyRef to an AssemblyDef.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal readonly struct AssemblyReferenceBinding
{
private readonly AssemblyIdentity? _referenceIdentity;
private readonly int _definitionIndex;
private readonly int _versionDifference;
/// <summary>
/// Failed binding.
/// </summary>
public AssemblyReferenceBinding(AssemblyIdentity referenceIdentity)
{
Debug.Assert(referenceIdentity != null);
_referenceIdentity = referenceIdentity;
_definitionIndex = -1;
_versionDifference = 0;
}
/// <summary>
/// Successful binding.
/// </summary>
public AssemblyReferenceBinding(AssemblyIdentity referenceIdentity, int definitionIndex, int versionDifference = 0)
{
Debug.Assert(referenceIdentity != null);
Debug.Assert(definitionIndex >= 0);
Debug.Assert(versionDifference >= -1 && versionDifference <= +1);
_referenceIdentity = referenceIdentity;
_definitionIndex = definitionIndex;
_versionDifference = versionDifference;
}
/// <summary>
/// Returns true if the reference was matched with the identity of the assembly being built.
/// </summary>
internal bool BoundToAssemblyBeingBuilt
{
get { return _definitionIndex == 0; }
}
/// <summary>
/// True if the definition index is available (reference was successfully matched with the definition).
/// </summary>
internal bool IsBound
{
get
{
return _definitionIndex >= 0;
}
}
/// <summary>
/// 0 if the reference is equivalent to the definition.
/// -1 if version of the matched definition is lower than version of the reference, but the reference otherwise matches the definition.
/// +1 if version of the matched definition is higher than version of the reference, but the reference otherwise matches the definition.
///
/// Undefined unless <see cref="IsBound"/> is true.
/// </summary>
internal int VersionDifference
{
get
{
Debug.Assert(IsBound);
return _versionDifference;
}
}
/// <summary>
/// Index into assembly definition list.
/// Undefined unless <see cref="IsBound"/> is true.
/// </summary>
internal int DefinitionIndex
{
get
{
Debug.Assert(IsBound);
return _definitionIndex;
}
}
internal AssemblyIdentity? ReferenceIdentity
{
get
{
return _referenceIdentity;
}
}
private string GetDebuggerDisplay()
{
var displayName = ReferenceIdentity?.GetDisplayName() ?? "";
return IsBound ? displayName + " -> #" + DefinitionIndex + (VersionDifference != 0 ? " VersionDiff=" + VersionDifference : "") : "unbound";
}
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Test/Semantic/Semantics/FieldInitializerBindingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class FieldInitializerBindingTests : CompilingTestBase
{
[Fact]
public void NoInitializers()
{
var source = @"
class C
{
static int s1;
int i1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ConstantInstanceInitializer()
{
var source = @"
class C
{
static int s1;
int i1 = 1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ConstantStaticInitializer()
{
var source = @"
class C
{
static int s1 = 1;
int i1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ExpressionInstanceInitializer()
{
var source = @"
class C
{
static int s1;
int i1 = 1 + Goo();
static int Goo() { return 1; }
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1 + Goo()", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ExpressionStaticInitializer()
{
var source = @"
class C
{
static int s1 = 1 + Goo();
int i1;
static int Goo() { return 1; }
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1 + Goo()", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void InitializerOrder()
{
var source = @"
class C
{
static int s1 = 1;
static int s2 = 2;
static int s3 = 3;
int i1 = 1;
int i2 = 2;
int i3 = 3;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 4),
new ExpectedInitializer("s3", "3", lineNumber: 5),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 6),
new ExpectedInitializer("i2", "2", lineNumber: 7),
new ExpectedInitializer("i3", "3", lineNumber: 8),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void AllPartialClasses()
{
var source = @"
partial class C
{
static int s1 = 1;
int i1 = 1;
}
partial class C
{
static int s2 = 2;
int i2 = 2;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 8),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
new ExpectedInitializer("i2", "2", lineNumber: 9),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void SomePartialClasses()
{
var source = @"
partial class C
{
static int s1 = 1;
int i1 = 1;
}
partial class C
{
static int s2 = 2;
int i2 = 2;
}
partial class C
{
static int s3;
int i3;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 8),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
new ExpectedInitializer("i2", "2", lineNumber: 9),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void Events()
{
var source = @"
class C
{
static event System.Action e = MakeAction(1);
event System.Action f = MakeAction(2);
static System.Action MakeAction(int x) { return null; }
}}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("e", "MakeAction(1)", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("f", "MakeAction(2)", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
private static void CompileAndCheckInitializers(string source, IEnumerable<ExpectedInitializer> expectedInstanceInitializers, IEnumerable<ExpectedInitializer> expectedStaticInitializers)
{
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees.First();
var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single();
var boundInstanceInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers);
CheckBoundInitializers(expectedInstanceInitializers, syntaxTree, boundInstanceInitializers, isStatic: false);
var boundStaticInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers);
CheckBoundInitializers(expectedStaticInitializers, syntaxTree, boundStaticInitializers, isStatic: true);
}
private static void CheckBoundInitializers(IEnumerable<ExpectedInitializer> expectedInitializers, SyntaxTree syntaxTree, ImmutableArray<BoundInitializer> boundInitializers, bool isStatic)
{
if (expectedInitializers == null)
{
Assert.Equal(0, boundInitializers.Length);
}
else
{
Assert.True(!boundInitializers.IsEmpty, "Expected non-null non-empty bound initializers");
int numInitializers = expectedInitializers.Count();
Assert.Equal(numInitializers, boundInitializers.Length);
int i = 0;
foreach (var expectedInitializer in expectedInitializers)
{
var boundInit = boundInitializers[i++];
Assert.Equal(BoundKind.FieldEqualsValue, boundInit.Kind);
var boundFieldInit = (BoundFieldEqualsValue)boundInit;
var initValueSyntax = boundFieldInit.Value.Syntax;
Assert.Same(initValueSyntax.Parent, boundInit.Syntax);
Assert.Equal(expectedInitializer.InitialValue, initValueSyntax.ToFullString());
var initValueLineNumber = syntaxTree.GetLineSpan(initValueSyntax.Span).StartLinePosition.Line;
Assert.Equal(expectedInitializer.LineNumber, initValueLineNumber);
Assert.Equal(expectedInitializer.FieldName, boundFieldInit.Field.Name);
}
}
}
private static ImmutableArray<BoundInitializer> BindInitializersWithoutDiagnostics(SourceNamedTypeSymbol typeSymbol, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
ImportChain unused;
var boundInitializers = ArrayBuilder<BoundInitializer>.GetInstance();
Binder.BindRegularCSharpFieldInitializers(
typeSymbol.DeclaringCompilation,
initializers,
boundInitializers,
new BindingDiagnosticBag(diagnostics),
firstDebugImports: out unused);
diagnostics.Verify();
diagnostics.Free();
return boundInitializers.ToImmutableAndFree();
}
private class ExpectedInitializer
{
public string FieldName { get; }
public string InitialValue { get; }
public int LineNumber { get; } //0-indexed
public ExpectedInitializer(string fieldName, string initialValue, int lineNumber)
{
this.FieldName = fieldName;
this.InitialValue = initialValue;
this.LineNumber = lineNumber;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class FieldInitializerBindingTests : CompilingTestBase
{
[Fact]
public void NoInitializers()
{
var source = @"
class C
{
static int s1;
int i1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ConstantInstanceInitializer()
{
var source = @"
class C
{
static int s1;
int i1 = 1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ConstantStaticInitializer()
{
var source = @"
class C
{
static int s1 = 1;
int i1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ExpressionInstanceInitializer()
{
var source = @"
class C
{
static int s1;
int i1 = 1 + Goo();
static int Goo() { return 1; }
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1 + Goo()", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ExpressionStaticInitializer()
{
var source = @"
class C
{
static int s1 = 1 + Goo();
int i1;
static int Goo() { return 1; }
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1 + Goo()", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void InitializerOrder()
{
var source = @"
class C
{
static int s1 = 1;
static int s2 = 2;
static int s3 = 3;
int i1 = 1;
int i2 = 2;
int i3 = 3;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 4),
new ExpectedInitializer("s3", "3", lineNumber: 5),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 6),
new ExpectedInitializer("i2", "2", lineNumber: 7),
new ExpectedInitializer("i3", "3", lineNumber: 8),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void AllPartialClasses()
{
var source = @"
partial class C
{
static int s1 = 1;
int i1 = 1;
}
partial class C
{
static int s2 = 2;
int i2 = 2;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 8),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
new ExpectedInitializer("i2", "2", lineNumber: 9),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void SomePartialClasses()
{
var source = @"
partial class C
{
static int s1 = 1;
int i1 = 1;
}
partial class C
{
static int s2 = 2;
int i2 = 2;
}
partial class C
{
static int s3;
int i3;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 8),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
new ExpectedInitializer("i2", "2", lineNumber: 9),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void Events()
{
var source = @"
class C
{
static event System.Action e = MakeAction(1);
event System.Action f = MakeAction(2);
static System.Action MakeAction(int x) { return null; }
}}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("e", "MakeAction(1)", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("f", "MakeAction(2)", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
private static void CompileAndCheckInitializers(string source, IEnumerable<ExpectedInitializer> expectedInstanceInitializers, IEnumerable<ExpectedInitializer> expectedStaticInitializers)
{
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees.First();
var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single();
var boundInstanceInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers);
CheckBoundInitializers(expectedInstanceInitializers, syntaxTree, boundInstanceInitializers, isStatic: false);
var boundStaticInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers);
CheckBoundInitializers(expectedStaticInitializers, syntaxTree, boundStaticInitializers, isStatic: true);
}
private static void CheckBoundInitializers(IEnumerable<ExpectedInitializer> expectedInitializers, SyntaxTree syntaxTree, ImmutableArray<BoundInitializer> boundInitializers, bool isStatic)
{
if (expectedInitializers == null)
{
Assert.Equal(0, boundInitializers.Length);
}
else
{
Assert.True(!boundInitializers.IsEmpty, "Expected non-null non-empty bound initializers");
int numInitializers = expectedInitializers.Count();
Assert.Equal(numInitializers, boundInitializers.Length);
int i = 0;
foreach (var expectedInitializer in expectedInitializers)
{
var boundInit = boundInitializers[i++];
Assert.Equal(BoundKind.FieldEqualsValue, boundInit.Kind);
var boundFieldInit = (BoundFieldEqualsValue)boundInit;
var initValueSyntax = boundFieldInit.Value.Syntax;
Assert.Same(initValueSyntax.Parent, boundInit.Syntax);
Assert.Equal(expectedInitializer.InitialValue, initValueSyntax.ToFullString());
var initValueLineNumber = syntaxTree.GetLineSpan(initValueSyntax.Span).StartLinePosition.Line;
Assert.Equal(expectedInitializer.LineNumber, initValueLineNumber);
Assert.Equal(expectedInitializer.FieldName, boundFieldInit.Field.Name);
}
}
}
private static ImmutableArray<BoundInitializer> BindInitializersWithoutDiagnostics(SourceNamedTypeSymbol typeSymbol, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
ImportChain unused;
var boundInitializers = ArrayBuilder<BoundInitializer>.GetInstance();
Binder.BindRegularCSharpFieldInitializers(
typeSymbol.DeclaringCompilation,
initializers,
boundInitializers,
new BindingDiagnosticBag(diagnostics),
firstDebugImports: out unused);
diagnostics.Verify();
diagnostics.Free();
return boundInitializers.ToImmutableAndFree();
}
private class ExpectedInitializer
{
public string FieldName { get; }
public string InitialValue { get; }
public int LineNumber { get; } //0-indexed
public ExpectedInitializer(string fieldName, string initialValue, int lineNumber)
{
this.FieldName = fieldName;
this.InitialValue = initialValue;
this.LineNumber = lineNumber;
}
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/FSharpDebugLocationInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Debugging;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging
{
internal readonly struct FSharpDebugLocationInfo
{
internal readonly DebugLocationInfo UnderlyingObject;
public FSharpDebugLocationInfo(string name, int lineOffset)
=> UnderlyingObject = new DebugLocationInfo(name, lineOffset);
public readonly string Name => UnderlyingObject.Name;
public readonly int LineOffset => UnderlyingObject.LineOffset;
internal bool IsDefault => UnderlyingObject.IsDefault;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Debugging;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging
{
internal readonly struct FSharpDebugLocationInfo
{
internal readonly DebugLocationInfo UnderlyingObject;
public FSharpDebugLocationInfo(string name, int lineOffset)
=> UnderlyingObject = new DebugLocationInfo(name, lineOffset);
public readonly string Name => UnderlyingObject.Name;
public readonly int LineOffset => UnderlyingObject.LineOffset;
internal bool IsDefault => UnderlyingObject.IsDefault;
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs | // Licensed to the .NET Foundation under one or more 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.Xml.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal interface ICodeStyleOption : IObjectWritable
{
XElement ToXElement();
object? Value { get; }
NotificationOption2 Notification { get; }
ICodeStyleOption WithValue(object value);
ICodeStyleOption WithNotification(NotificationOption2 notification);
ICodeStyleOption AsCodeStyleOption<TCodeStyleOption>();
#if !CODE_STYLE
ICodeStyleOption AsPublicCodeStyleOption();
#endif
}
/// <summary>
/// Represents a code style option and an associated notification option. Supports
/// being instantiated with T as a <see cref="bool"/> or an <c>enum type</c>.
///
/// CodeStyleOption also has some basic support for migration a <see cref="bool"/> option
/// forward to an <c>enum type</c> option. Specifically, if a previously serialized
/// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false'
/// values will be migrated to have the 0-value of the enum, and 'true' values will be
/// migrated to have the 1-value of the enum.
///
/// Similarly, enum-type code options will serialize out in a way that is compatible with
/// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1
/// then those values will write back as false/true.
/// </summary>
internal sealed partial class CodeStyleOption2<T> : ICodeStyleOption, IEquatable<CodeStyleOption2<T>?>
{
static CodeStyleOption2()
{
ObjectBinder.RegisterTypeReader(typeof(CodeStyleOption2<T>), ReadFrom);
}
public static CodeStyleOption2<T> Default => new(default!, NotificationOption2.Silent);
private const int SerializationVersion = 1;
private readonly NotificationOption2 _notification;
public CodeStyleOption2(T value, NotificationOption2 notification)
{
Value = value;
_notification = notification ?? throw new ArgumentNullException(nameof(notification));
}
public T Value { get; }
object? ICodeStyleOption.Value => this.Value;
ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption2<T>((T)value, Notification);
ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption2<T>(Value, notification);
#if CODE_STYLE
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this;
#else
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>()
=> this is TCodeStyleOption ? this : (ICodeStyleOption)new CodeStyleOption<T>(this);
ICodeStyleOption ICodeStyleOption.AsPublicCodeStyleOption() => new CodeStyleOption<T>(this);
#endif
private int EnumValueAsInt32 => (int)(object)Value!;
public NotificationOption2 Notification
{
get => _notification;
}
public XElement ToXElement() =>
new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat.
new XAttribute(nameof(SerializationVersion), SerializationVersion),
new XAttribute("Type", GetTypeNameForSerialization()),
new XAttribute(nameof(Value), GetValueForSerialization()),
new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
private object GetValueForSerialization()
{
if (typeof(T) == typeof(string))
{
return Value!;
}
else if (typeof(T) == typeof(bool))
{
return Value!;
}
else if (IsZeroOrOneValueOfEnum())
{
return EnumValueAsInt32 == 1;
}
else
{
return EnumValueAsInt32;
}
}
private string GetTypeNameForSerialization()
{
if (typeof(T) == typeof(string))
{
return nameof(String);
}
if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum())
{
return nameof(Boolean);
}
else
{
return nameof(Int32);
}
}
private bool IsZeroOrOneValueOfEnum()
{
var intVal = EnumValueAsInt32;
return intVal == 0 || intVal == 1;
}
public static CodeStyleOption2<T> FromXElement(XElement element)
{
var typeAttribute = element.Attribute("Type");
var valueAttribute = element.Attribute(nameof(Value));
var severityAttribute = element.Attribute(nameof(DiagnosticSeverity));
var version = (int?)element.Attribute(nameof(SerializationVersion));
if (typeAttribute == null || valueAttribute == null || severityAttribute == null)
{
// data from storage is corrupt, or nothing has been stored yet.
return Default;
}
if (version != SerializationVersion)
{
return Default;
}
var parser = GetParser(typeAttribute.Value);
var value = parser(valueAttribute.Value);
var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value);
return new CodeStyleOption2<T>(value, severity switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
_ => throw new ArgumentException(nameof(element)),
});
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteValue(GetValueForSerialization());
writer.WriteInt32((int)(Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
}
public static CodeStyleOption2<object> ReadFrom(ObjectReader reader)
{
return new CodeStyleOption2<object>(
reader.ReadValue(),
(DiagnosticSeverity)reader.ReadInt32() switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
var v => throw ExceptionUtilities.UnexpectedValue(v),
});
}
private static Func<string, T> GetParser(string type)
=> type switch
{
nameof(Boolean) =>
// Try to map a boolean value. Either map it to true/false if we're a
// CodeStyleOption<bool> or map it to the 0 or 1 value for an enum if we're
// a CodeStyleOption<SomeEnumType>.
(Func<string, T>)(v => Convert(bool.Parse(v))),
nameof(Int32) => v => Convert(int.Parse(v)),
nameof(String) => v => (T)(object)v,
_ => throw new ArgumentException(nameof(type)),
};
private static T Convert(bool b)
{
// If we had a bool and we wanted a bool, then just return this value.
if (typeof(T) == typeof(bool))
{
return (T)(object)b;
}
// Map booleans to the 1/0 value of the enum.
return b ? (T)(object)1 : (T)(object)0;
}
private static T Convert(int i)
{
// We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default.
if (typeof(T) == typeof(bool))
{
return (T)(object)(i == 1);
}
// If had an int and we wanted an enum, then just return this value.
return (T)(object)(i);
}
public bool Equals(CodeStyleOption2<T>? other)
{
return other is not null
&& EqualityComparer<T>.Default.Equals(Value, other.Value)
&& Notification == other.Notification;
}
public override bool Equals(object? obj)
=> obj is CodeStyleOption2<T> option &&
Equals(option);
public override int GetHashCode()
=> unchecked((Notification.GetHashCode() * (int)0xA5555529) + EqualityComparer<T>.Default.GetHashCode(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;
using System.Collections.Generic;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal interface ICodeStyleOption : IObjectWritable
{
XElement ToXElement();
object? Value { get; }
NotificationOption2 Notification { get; }
ICodeStyleOption WithValue(object value);
ICodeStyleOption WithNotification(NotificationOption2 notification);
ICodeStyleOption AsCodeStyleOption<TCodeStyleOption>();
#if !CODE_STYLE
ICodeStyleOption AsPublicCodeStyleOption();
#endif
}
/// <summary>
/// Represents a code style option and an associated notification option. Supports
/// being instantiated with T as a <see cref="bool"/> or an <c>enum type</c>.
///
/// CodeStyleOption also has some basic support for migration a <see cref="bool"/> option
/// forward to an <c>enum type</c> option. Specifically, if a previously serialized
/// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false'
/// values will be migrated to have the 0-value of the enum, and 'true' values will be
/// migrated to have the 1-value of the enum.
///
/// Similarly, enum-type code options will serialize out in a way that is compatible with
/// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1
/// then those values will write back as false/true.
/// </summary>
internal sealed partial class CodeStyleOption2<T> : ICodeStyleOption, IEquatable<CodeStyleOption2<T>?>
{
static CodeStyleOption2()
{
ObjectBinder.RegisterTypeReader(typeof(CodeStyleOption2<T>), ReadFrom);
}
public static CodeStyleOption2<T> Default => new(default!, NotificationOption2.Silent);
private const int SerializationVersion = 1;
private readonly NotificationOption2 _notification;
public CodeStyleOption2(T value, NotificationOption2 notification)
{
Value = value;
_notification = notification ?? throw new ArgumentNullException(nameof(notification));
}
public T Value { get; }
object? ICodeStyleOption.Value => this.Value;
ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption2<T>((T)value, Notification);
ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption2<T>(Value, notification);
#if CODE_STYLE
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this;
#else
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>()
=> this is TCodeStyleOption ? this : (ICodeStyleOption)new CodeStyleOption<T>(this);
ICodeStyleOption ICodeStyleOption.AsPublicCodeStyleOption() => new CodeStyleOption<T>(this);
#endif
private int EnumValueAsInt32 => (int)(object)Value!;
public NotificationOption2 Notification
{
get => _notification;
}
public XElement ToXElement() =>
new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat.
new XAttribute(nameof(SerializationVersion), SerializationVersion),
new XAttribute("Type", GetTypeNameForSerialization()),
new XAttribute(nameof(Value), GetValueForSerialization()),
new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
private object GetValueForSerialization()
{
if (typeof(T) == typeof(string))
{
return Value!;
}
else if (typeof(T) == typeof(bool))
{
return Value!;
}
else if (IsZeroOrOneValueOfEnum())
{
return EnumValueAsInt32 == 1;
}
else
{
return EnumValueAsInt32;
}
}
private string GetTypeNameForSerialization()
{
if (typeof(T) == typeof(string))
{
return nameof(String);
}
if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum())
{
return nameof(Boolean);
}
else
{
return nameof(Int32);
}
}
private bool IsZeroOrOneValueOfEnum()
{
var intVal = EnumValueAsInt32;
return intVal == 0 || intVal == 1;
}
public static CodeStyleOption2<T> FromXElement(XElement element)
{
var typeAttribute = element.Attribute("Type");
var valueAttribute = element.Attribute(nameof(Value));
var severityAttribute = element.Attribute(nameof(DiagnosticSeverity));
var version = (int?)element.Attribute(nameof(SerializationVersion));
if (typeAttribute == null || valueAttribute == null || severityAttribute == null)
{
// data from storage is corrupt, or nothing has been stored yet.
return Default;
}
if (version != SerializationVersion)
{
return Default;
}
var parser = GetParser(typeAttribute.Value);
var value = parser(valueAttribute.Value);
var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value);
return new CodeStyleOption2<T>(value, severity switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
_ => throw new ArgumentException(nameof(element)),
});
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteValue(GetValueForSerialization());
writer.WriteInt32((int)(Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
}
public static CodeStyleOption2<object> ReadFrom(ObjectReader reader)
{
return new CodeStyleOption2<object>(
reader.ReadValue(),
(DiagnosticSeverity)reader.ReadInt32() switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
var v => throw ExceptionUtilities.UnexpectedValue(v),
});
}
private static Func<string, T> GetParser(string type)
=> type switch
{
nameof(Boolean) =>
// Try to map a boolean value. Either map it to true/false if we're a
// CodeStyleOption<bool> or map it to the 0 or 1 value for an enum if we're
// a CodeStyleOption<SomeEnumType>.
(Func<string, T>)(v => Convert(bool.Parse(v))),
nameof(Int32) => v => Convert(int.Parse(v)),
nameof(String) => v => (T)(object)v,
_ => throw new ArgumentException(nameof(type)),
};
private static T Convert(bool b)
{
// If we had a bool and we wanted a bool, then just return this value.
if (typeof(T) == typeof(bool))
{
return (T)(object)b;
}
// Map booleans to the 1/0 value of the enum.
return b ? (T)(object)1 : (T)(object)0;
}
private static T Convert(int i)
{
// We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default.
if (typeof(T) == typeof(bool))
{
return (T)(object)(i == 1);
}
// If had an int and we wanted an enum, then just return this value.
return (T)(object)(i);
}
public bool Equals(CodeStyleOption2<T>? other)
{
return other is not null
&& EqualityComparer<T>.Default.Equals(Value, other.Value)
&& Notification == other.Notification;
}
public override bool Equals(object? obj)
=> obj is CodeStyleOption2<T> option &&
Equals(option);
public override int GetHashCode()
=> unchecked((Notification.GetHashCode() * (int)0xA5555529) + EqualityComparer<T>.Default.GetHashCode(Value!));
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/MenuItemContainerTemplateSelector.cs | // Licensed to the .NET Foundation under one or more 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.Windows;
using System.Windows.Controls;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph
{
internal class MenuItemContainerTemplateSelector : ItemContainerTemplateSelector
{
// By default, ContextMenu would create same MenuItem for each ViewModel from ItemSource,
// this would override the default behavior, and let contextMenu create different MenuItem
// based on the ViewModel's type
public override DataTemplate SelectTemplate(object item, ItemsControl parentItemsControl)
{
if (item is HeaderMenuItemViewModel)
{
// Template for Header
return (DataTemplate)parentItemsControl.FindResource("HeaderMenuItemTemplate");
}
if (item is TargetMenuItemViewModel)
{
// Template for Target
return (DataTemplate)parentItemsControl.FindResource("TargetMenuItemTemplate");
}
if (item is MemberMenuItemViewModel)
{
// Template for member
return (DataTemplate)parentItemsControl.FindResource("MemberMenuItemTemplate");
}
throw ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Windows;
using System.Windows.Controls;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph
{
internal class MenuItemContainerTemplateSelector : ItemContainerTemplateSelector
{
// By default, ContextMenu would create same MenuItem for each ViewModel from ItemSource,
// this would override the default behavior, and let contextMenu create different MenuItem
// based on the ViewModel's type
public override DataTemplate SelectTemplate(object item, ItemsControl parentItemsControl)
{
if (item is HeaderMenuItemViewModel)
{
// Template for Header
return (DataTemplate)parentItemsControl.FindResource("HeaderMenuItemTemplate");
}
if (item is TargetMenuItemViewModel)
{
// Template for Target
return (DataTemplate)parentItemsControl.FindResource("TargetMenuItemTemplate");
}
if (item is MemberMenuItemViewModel)
{
// Template for member
return (DataTemplate)parentItemsControl.FindResource("MemberMenuItemTemplate");
}
throw ExceptionUtilities.Unreachable;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Test/PdbUtilities/Shared/DateTimeUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Roslyn.Utilities
{
internal static class DateTimeUtilities
{
// From DateTime.cs.
private const long TicksMask = 0x3FFFFFFFFFFFFFFF;
internal static DateTime ToDateTime(double raw)
{
// This mechanism for getting the tick count from the underlying ulong field is copied
// from System.DateTime.InternalTicks (ndp\clr\src\BCL\System\DateTime.cs).
var tickCount = BitConverter.DoubleToInt64Bits(raw) & TicksMask;
return new DateTime(tickCount);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Roslyn.Utilities
{
internal static class DateTimeUtilities
{
// From DateTime.cs.
private const long TicksMask = 0x3FFFFFFFFFFFFFFF;
internal static DateTime ToDateTime(double raw)
{
// This mechanism for getting the tick count from the underlying ulong field is copied
// from System.DateTime.InternalTicks (ndp\clr\src\BCL\System\DateTime.cs).
var tickCount = BitConverter.DoubleToInt64Bits(raw) & TicksMask;
return new DateTime(tickCount);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/Core/Portable/DesignerAttribute/IDesignerAttributeListener.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.DesignerAttribute
{
/// <summary>
/// Callback the host (VS) passes to the OOP service to allow it to send batch notifications
/// about designer attribute info. There is no guarantee that the host will have done anything
/// with this data when the callback returns, only that it will try to inform the project system
/// about the designer attribute info in the future.
/// </summary>
internal interface IDesignerAttributeListener
{
ValueTask OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken);
ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.DesignerAttribute
{
/// <summary>
/// Callback the host (VS) passes to the OOP service to allow it to send batch notifications
/// about designer attribute info. There is no guarantee that the host will have done anything
/// with this data when the callback returns, only that it will try to inform the project system
/// about the designer attribute info in the future.
/// </summary>
internal interface IDesignerAttributeListener
{
ValueTask OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken);
ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.ja.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="ja" original="../WorkspaceDesktopResources.resx">
<body>
<trans-unit id="Invalid_assembly_name">
<source>Invalid assembly name</source>
<target state="translated">無効なアセンブリ名</target>
<note />
</trans-unit>
<trans-unit id="Invalid_characters_in_assembly_name">
<source>Invalid characters in assembly name</source>
<target state="translated">アセンブリ名に無効な文字があります</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../WorkspaceDesktopResources.resx">
<body>
<trans-unit id="Invalid_assembly_name">
<source>Invalid assembly name</source>
<target state="translated">無効なアセンブリ名</target>
<note />
</trans-unit>
<trans-unit id="Invalid_characters_in_assembly_name">
<source>Invalid characters in assembly name</source>
<target state="translated">アセンブリ名に無効な文字があります</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Scripting/CSharp/Hosting/ObjectFormatter/CSharpPrimitiveFormatter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting
{
using static ObjectFormatterHelpers;
internal class CSharpPrimitiveFormatter : CommonPrimitiveFormatter
{
protected override string NullLiteral => ObjectDisplay.NullLiteral;
protected override string FormatLiteral(bool value)
{
return ObjectDisplay.FormatLiteral(value);
}
protected override string FormatLiteral(string value, bool useQuotes, bool escapeNonPrintable, int numberRadix = NumberRadixDecimal)
{
var options = GetObjectDisplayOptions(useQuotes: useQuotes, escapeNonPrintable: escapeNonPrintable, numberRadix: numberRadix);
return ObjectDisplay.FormatLiteral(value, options);
}
protected override string FormatLiteral(char c, bool useQuotes, bool escapeNonPrintable, bool includeCodePoints = false, int numberRadix = NumberRadixDecimal)
{
var options = GetObjectDisplayOptions(useQuotes: useQuotes, escapeNonPrintable: escapeNonPrintable, includeCodePoints: includeCodePoints, numberRadix: numberRadix);
return ObjectDisplay.FormatLiteral(c, options);
}
protected override string FormatLiteral(sbyte value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(byte value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(short value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(ushort value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(int value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(uint value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(long value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(ulong value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(double value, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo);
}
protected override string FormatLiteral(float value, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo);
}
protected override string FormatLiteral(decimal value, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo);
}
protected override string FormatLiteral(DateTime value, CultureInfo cultureInfo = null)
{
// DateTime is not primitive in C#
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting
{
using static ObjectFormatterHelpers;
internal class CSharpPrimitiveFormatter : CommonPrimitiveFormatter
{
protected override string NullLiteral => ObjectDisplay.NullLiteral;
protected override string FormatLiteral(bool value)
{
return ObjectDisplay.FormatLiteral(value);
}
protected override string FormatLiteral(string value, bool useQuotes, bool escapeNonPrintable, int numberRadix = NumberRadixDecimal)
{
var options = GetObjectDisplayOptions(useQuotes: useQuotes, escapeNonPrintable: escapeNonPrintable, numberRadix: numberRadix);
return ObjectDisplay.FormatLiteral(value, options);
}
protected override string FormatLiteral(char c, bool useQuotes, bool escapeNonPrintable, bool includeCodePoints = false, int numberRadix = NumberRadixDecimal)
{
var options = GetObjectDisplayOptions(useQuotes: useQuotes, escapeNonPrintable: escapeNonPrintable, includeCodePoints: includeCodePoints, numberRadix: numberRadix);
return ObjectDisplay.FormatLiteral(c, options);
}
protected override string FormatLiteral(sbyte value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(byte value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(short value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(ushort value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(int value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(uint value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(long value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(ulong value, int numberRadix = NumberRadixDecimal, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix: numberRadix), cultureInfo);
}
protected override string FormatLiteral(double value, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo);
}
protected override string FormatLiteral(float value, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo);
}
protected override string FormatLiteral(decimal value, CultureInfo cultureInfo = null)
{
return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo);
}
protected override string FormatLiteral(DateTime value, CultureInfo cultureInfo = null)
{
// DateTime is not primitive in C#
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/Core/Portable/Workspace/Host/Status/IWorkspaceStatusService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Provides workspace status
///
/// this is an work in-progress interface, subject to be changed as we work on prototype.
///
/// it can completely removed at the end or new APIs can added and removed as prototype going on
/// no one except one in the prototype group should use this interface.
///
/// tracking issue - https://github.com/dotnet/roslyn/issues/34415
/// </summary>
internal interface IWorkspaceStatusService : IWorkspaceService
{
/// <summary>
/// Indicate that status has changed
/// </summary>
event EventHandler StatusChanged;
/// <summary>
/// Wait until workspace is fully loaded
///
/// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages.
/// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can
/// deadlock
/// </summary>
Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken);
/// <summary>
/// Indicates whether workspace is fully loaded
///
/// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages.
/// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can
/// deadlock
/// </summary>
Task<bool> IsFullyLoadedAsync(CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Provides workspace status
///
/// this is an work in-progress interface, subject to be changed as we work on prototype.
///
/// it can completely removed at the end or new APIs can added and removed as prototype going on
/// no one except one in the prototype group should use this interface.
///
/// tracking issue - https://github.com/dotnet/roslyn/issues/34415
/// </summary>
internal interface IWorkspaceStatusService : IWorkspaceService
{
/// <summary>
/// Indicate that status has changed
/// </summary>
event EventHandler StatusChanged;
/// <summary>
/// Wait until workspace is fully loaded
///
/// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages.
/// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can
/// deadlock
/// </summary>
Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken);
/// <summary>
/// Indicates whether workspace is fully loaded
///
/// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages.
/// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can
/// deadlock
/// </summary>
Task<bool> IsFullyLoadedAsync(CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./docs/wiki/Runtime-code-generation-using-Roslyn-compilations-in-.NET-Core-App.md | A question that arises when emitting assemblies via Roslyn Compilation APIs in .NET Core app is how to create MetadataReferences for .NET Core Framework libraries (such as ```System.Runtime.dll```, ```System.IO.dll```, etc.).
There are two approaches to runtime code generation:
### Compile against runtime (implementation) assemblies
This is what [C# Scripting API](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Scripting-API-Samples.md) currently does. There are a few gotchas with this approach:
- in .NET Core 1.x the implementation assemblies currently contain some duplicate public types (fixed in 2.0, see https://github.com/dotnet/corefx/issues/5540).
- the implementation assemblies change with releases, so code that compiles against one version of CoreCLR might not compile against newer version.
The APIs are backward compatible, however compiler overload resolution might prefer an API added in the new version instead of the one that it used to pick before.
The Scripting APIs use Trusted Platform Assembly list to locate the implementation assemblies on CoreCLR.
You can get a list of semicolon-separated paths to these .dlls like so (see [RuntimeMetadataReferenceResolver](http://sourceroslyn.io/#Microsoft.CodeAnalysis.Scripting/Hosting/Resolvers/RuntimeMetadataReferenceResolver.cs) implementation):
```C#
AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")
```
Enumerate this and find paths to assemblies you're interested in (you'll find "mscorlib.dll" on that list too).
You can use RuntimeMetadataReferenceResolver to do this for you.
### Compile against reference (contract) assemblies
This is what the compiler does when invoked from msbuild. You need to decide what reference assemblies to use (e.g. ```netstandard1.5```). Once you decide, you need to get them from nuget packages and distribute them with your application, e.g. in a form of embedded resources. Then in your application extract the binaries from resources and create MetadataReferences for them.
To find out what reference assemblies you need and where to get them you can create an empty .NET Core library, set the target framework to the one you need to target, build using ```msbuild /v:detailed``` and look for ```csc.exe``` invocation in msbuild output. The command line will list all references the C# compiler uses to build the library (look for ```/reference``` command line arguments).
Alternatively, projects that use .NET SDK can set `PreserveCompilationContext` build property to `true`. Publishing such project will copy reference assemblies for the framework the project targets to a `refs` sub-directory of the `publish` directory.
This approach has the benefit of stable APIs - the reference assemblies will never change, so your code will work on future versions of CoreCLR runtimes.
---
Related issues:
- https://github.com/dotnet/roslyn/issues/16846
| A question that arises when emitting assemblies via Roslyn Compilation APIs in .NET Core app is how to create MetadataReferences for .NET Core Framework libraries (such as ```System.Runtime.dll```, ```System.IO.dll```, etc.).
There are two approaches to runtime code generation:
### Compile against runtime (implementation) assemblies
This is what [C# Scripting API](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Scripting-API-Samples.md) currently does. There are a few gotchas with this approach:
- in .NET Core 1.x the implementation assemblies currently contain some duplicate public types (fixed in 2.0, see https://github.com/dotnet/corefx/issues/5540).
- the implementation assemblies change with releases, so code that compiles against one version of CoreCLR might not compile against newer version.
The APIs are backward compatible, however compiler overload resolution might prefer an API added in the new version instead of the one that it used to pick before.
The Scripting APIs use Trusted Platform Assembly list to locate the implementation assemblies on CoreCLR.
You can get a list of semicolon-separated paths to these .dlls like so (see [RuntimeMetadataReferenceResolver](http://sourceroslyn.io/#Microsoft.CodeAnalysis.Scripting/Hosting/Resolvers/RuntimeMetadataReferenceResolver.cs) implementation):
```C#
AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")
```
Enumerate this and find paths to assemblies you're interested in (you'll find "mscorlib.dll" on that list too).
You can use RuntimeMetadataReferenceResolver to do this for you.
### Compile against reference (contract) assemblies
This is what the compiler does when invoked from msbuild. You need to decide what reference assemblies to use (e.g. ```netstandard1.5```). Once you decide, you need to get them from nuget packages and distribute them with your application, e.g. in a form of embedded resources. Then in your application extract the binaries from resources and create MetadataReferences for them.
To find out what reference assemblies you need and where to get them you can create an empty .NET Core library, set the target framework to the one you need to target, build using ```msbuild /v:detailed``` and look for ```csc.exe``` invocation in msbuild output. The command line will list all references the C# compiler uses to build the library (look for ```/reference``` command line arguments).
Alternatively, projects that use .NET SDK can set `PreserveCompilationContext` build property to `true`. Publishing such project will copy reference assemblies for the framework the project targets to a `refs` sub-directory of the `publish` directory.
This approach has the benefit of stable APIs - the reference assemblies will never change, so your code will work on future versions of CoreCLR runtimes.
---
Related issues:
- https://github.com/dotnet/roslyn/issues/16846
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller_OnCaretPositionChanged.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Implementation.IntelliSense.SignatureHelp
{
internal partial class Controller
{
internal override void OnCaretPositionChanged(object sender, EventArgs args)
{
AssertIsForeground();
OnCaretPositionChanged();
}
private void OnCaretPositionChanged()
=> Retrigger();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Implementation.IntelliSense.SignatureHelp
{
internal partial class Controller
{
internal override void OnCaretPositionChanged(object sender, EventArgs args)
{
AssertIsForeground();
OnCaretPositionChanged();
}
private void OnCaretPositionChanged()
=> Retrigger();
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeCleanup;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.CSharp;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
[UseExportProvider]
public class CodeCleanupTests
{
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task RemoveUsings()
{
var code = @"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}
";
var expected = @"using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine();
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortUsings()
{
var code = @"using System.Collections.Generic;
using System;
class Program
{
static void Main(string[] args)
{
var list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
var expected = @"using System;
using System.Collections.Generic;
internal class Program
{
private static void Main(string[] args)
{
List<int> list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortGlobalUsings()
{
var code = @"using System.Threading.Tasks;
using System.Threading;
global using System.Collections.Generic;
global using System;
class Program
{
static async Task Main(string[] args)
{
Barrier b = new Barrier(0);
var list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
var expected = @"global using System;
global using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
internal class Program
{
private static async Task Main(string[] args)
{
Barrier b = new Barrier(0);
List<int> list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task GroupUsings()
{
var code = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
var expected = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
return AssertCodeCleanupResult(expected, code, systemUsingsFirst: false, separateUsingGroups: true);
}
[Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortAndGroupUsings()
{
var code = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
var expected = @"using System;
using M;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
return AssertCodeCleanupResult(expected, code, systemUsingsFirst: true, separateUsingGroups: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixAddRemoveBraces()
{
var code = @"class Program
{
void Method()
{
int a = 0;
if (a > 0)
a ++;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
int a = 0;
if (a > 0)
{
a++;
}
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task RemoveUnusedVariable()
{
var code = @"class Program
{
void Method()
{
int a;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixAccessibilityModifiers()
{
var code = @"class Program
{
void Method()
{
int a;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferOutside()
{
var code = @"namespace A
{
using System;
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = @"using System;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferInside()
{
var code = @"using System;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = @"namespace A
{
using System;
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
return AssertCodeCleanupResult(expected, code, InsideNamespaceOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferInsidePreserve()
{
var code = @"using System;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferOutsidePreserve()
{
var code = @"namespace A
{
using System;
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferOutside()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = @"using System;
using System.Collections.Generic;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
return AssertCodeCleanupResult(expected, code, OutsideNamespaceOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferInside()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = @"namespace A
{
using System;
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
return AssertCodeCleanupResult(expected, code, InsideNamespaceOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferInsidePreserve()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferOutsidePreserve()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption);
}
/// <summary>
/// Assert the expected code value equals the actual processed input <paramref name="code"/>.
/// </summary>
/// <param name="expected">The actual processed code to verify against.</param>
/// <param name="code">The input code to be processed and tested.</param>
/// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param>
/// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param>
/// <returns>The <see cref="Task"/> to test code cleanup.</returns>
private protected static Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false)
=> AssertCodeCleanupResult(expected, code, CSharpCodeStyleOptions.PreferOutsidePlacementWithSilentEnforcement, systemUsingsFirst, separateUsingGroups);
/// <summary>
/// Assert the expected code value equals the actual processed input <paramref name="code"/>.
/// </summary>
/// <param name="expected">The actual processed code to verify against.</param>
/// <param name="code">The input code to be processed and tested.</param>
/// <param name="preferredImportPlacement">Indicates the code style option for the preferred 'using' directives placement.</param>
/// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param>
/// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param>
/// <returns>The <see cref="Task"/> to test code cleanup.</returns>
private protected static async Task AssertCodeCleanupResult(string expected, string code, CodeStyleOption2<AddImportPlacement> preferredImportPlacement, bool systemUsingsFirst = true, bool separateUsingGroups = false)
{
using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf);
var solution = workspace.CurrentSolution
.WithOptions(workspace.Options
.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst)
.WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups)
.WithChangedOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredImportPlacement))
.WithAnalyzerReferences(new[]
{
new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile),
new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile)
});
workspace.TryApplyChanges(solution);
// register this workspace to solution crawler so that analyzer service associate itself with given workspace
var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider;
incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace);
var hostdoc = workspace.Documents.Single();
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var codeCleanupService = document.GetLanguageService<ICodeCleanupService>();
var enabledDiagnostics = codeCleanupService.GetAllDiagnostics();
var newDoc = await codeCleanupService.CleanupAsync(
document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None);
var actual = await newDoc.GetTextAsync();
Assert.Equal(expected, actual.ToString());
}
private static readonly CodeStyleOption2<AddImportPlacement> InsideNamespaceOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error);
private static readonly CodeStyleOption2<AddImportPlacement> OutsideNamespaceOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error);
private static readonly CodeStyleOption2<AddImportPlacement> InsidePreferPreservationOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.None);
private static readonly CodeStyleOption2<AddImportPlacement> OutsidePreferPreservationOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.None);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeCleanup;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.CSharp;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
[UseExportProvider]
public class CodeCleanupTests
{
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task RemoveUsings()
{
var code = @"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}
";
var expected = @"using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine();
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortUsings()
{
var code = @"using System.Collections.Generic;
using System;
class Program
{
static void Main(string[] args)
{
var list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
var expected = @"using System;
using System.Collections.Generic;
internal class Program
{
private static void Main(string[] args)
{
List<int> list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortGlobalUsings()
{
var code = @"using System.Threading.Tasks;
using System.Threading;
global using System.Collections.Generic;
global using System;
class Program
{
static async Task Main(string[] args)
{
Barrier b = new Barrier(0);
var list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
var expected = @"global using System;
global using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
internal class Program
{
private static async Task Main(string[] args)
{
Barrier b = new Barrier(0);
List<int> list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task GroupUsings()
{
var code = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
var expected = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
return AssertCodeCleanupResult(expected, code, systemUsingsFirst: false, separateUsingGroups: true);
}
[Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortAndGroupUsings()
{
var code = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
var expected = @"using System;
using M;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
return AssertCodeCleanupResult(expected, code, systemUsingsFirst: true, separateUsingGroups: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixAddRemoveBraces()
{
var code = @"class Program
{
void Method()
{
int a = 0;
if (a > 0)
a ++;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
int a = 0;
if (a > 0)
{
a++;
}
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task RemoveUnusedVariable()
{
var code = @"class Program
{
void Method()
{
int a;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixAccessibilityModifiers()
{
var code = @"class Program
{
void Method()
{
int a;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferOutside()
{
var code = @"namespace A
{
using System;
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = @"using System;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferInside()
{
var code = @"using System;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = @"namespace A
{
using System;
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
return AssertCodeCleanupResult(expected, code, InsideNamespaceOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferInsidePreserve()
{
var code = @"using System;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementPreferOutsidePreserve()
{
var code = @"namespace A
{
using System;
internal class Program
{
private void Method()
{
Console.WriteLine();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferOutside()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = @"using System;
using System.Collections.Generic;
namespace A
{
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
return AssertCodeCleanupResult(expected, code, OutsideNamespaceOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferInside()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = @"namespace A
{
using System;
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
return AssertCodeCleanupResult(expected, code, InsideNamespaceOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferInsidePreserve()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixUsingPlacementMixedPreferOutsidePreserve()
{
var code = @"using System;
namespace A
{
using System.Collections.Generic;
internal class Program
{
private void Method()
{
Console.WriteLine();
List<int> list = new List<int>();
}
}
}
";
var expected = code;
return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption);
}
/// <summary>
/// Assert the expected code value equals the actual processed input <paramref name="code"/>.
/// </summary>
/// <param name="expected">The actual processed code to verify against.</param>
/// <param name="code">The input code to be processed and tested.</param>
/// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param>
/// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param>
/// <returns>The <see cref="Task"/> to test code cleanup.</returns>
private protected static Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false)
=> AssertCodeCleanupResult(expected, code, CSharpCodeStyleOptions.PreferOutsidePlacementWithSilentEnforcement, systemUsingsFirst, separateUsingGroups);
/// <summary>
/// Assert the expected code value equals the actual processed input <paramref name="code"/>.
/// </summary>
/// <param name="expected">The actual processed code to verify against.</param>
/// <param name="code">The input code to be processed and tested.</param>
/// <param name="preferredImportPlacement">Indicates the code style option for the preferred 'using' directives placement.</param>
/// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param>
/// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param>
/// <returns>The <see cref="Task"/> to test code cleanup.</returns>
private protected static async Task AssertCodeCleanupResult(string expected, string code, CodeStyleOption2<AddImportPlacement> preferredImportPlacement, bool systemUsingsFirst = true, bool separateUsingGroups = false)
{
using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf);
var solution = workspace.CurrentSolution
.WithOptions(workspace.Options
.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst)
.WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups)
.WithChangedOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredImportPlacement))
.WithAnalyzerReferences(new[]
{
new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile),
new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile)
});
workspace.TryApplyChanges(solution);
// register this workspace to solution crawler so that analyzer service associate itself with given workspace
var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider;
incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace);
var hostdoc = workspace.Documents.Single();
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var codeCleanupService = document.GetLanguageService<ICodeCleanupService>();
var enabledDiagnostics = codeCleanupService.GetAllDiagnostics();
var newDoc = await codeCleanupService.CleanupAsync(
document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None);
var actual = await newDoc.GetTextAsync();
Assert.Equal(expected, actual.ToString());
}
private static readonly CodeStyleOption2<AddImportPlacement> InsideNamespaceOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error);
private static readonly CodeStyleOption2<AddImportPlacement> OutsideNamespaceOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error);
private static readonly CodeStyleOption2<AddImportPlacement> InsidePreferPreservationOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.None);
private static readonly CodeStyleOption2<AddImportPlacement> OutsidePreferPreservationOption =
new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.None);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/VisualBasic/Portable/Analysis/InitializerRewriter.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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Turns the bound initializers into a list of bound assignment statements
''' </summary>
Friend Module InitializerRewriter
''' <summary>
''' Builds a constructor body.
''' </summary>
''' <remarks>
''' Lowers initializers to fields assignments if not lowered yet and the first statement of the body isn't
''' a call to another constructor of the containing class.
''' </remarks>
''' <returns>
''' Bound block including
''' - call to a base constructor
''' - field initializers and top-level code
''' - remaining constructor statements (empty for a submission)
''' </returns>
Friend Function BuildConstructorBody(
compilationState As TypeCompilationState,
constructorMethod As MethodSymbol,
constructorInitializerOpt As BoundStatement,
processedInitializers As Binder.ProcessedFieldOrPropertyInitializers,
block As BoundBlock) As BoundBlock
Dim hasMyBaseConstructorCall As Boolean = False
Dim containingType = constructorMethod.ContainingType
If HasExplicitMeConstructorCall(block, containingType, hasMyBaseConstructorCall) AndAlso Not hasMyBaseConstructorCall Then
Return block
End If
' rewrite initializers just once, statements will be reused when emitting all constructors with field initializers:
If processedInitializers.InitializerStatements.IsDefault Then
processedInitializers.InitializerStatements = processedInitializers.BoundInitializers.SelectAsArray(AddressOf RewriteInitializerAsStatement)
Debug.Assert(processedInitializers.BoundInitializers.Length = processedInitializers.InitializerStatements.Length)
End If
Dim initializerStatements = processedInitializers.InitializerStatements
Dim blockStatements As ImmutableArray(Of BoundStatement) = block.Statements
Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance()
If constructorInitializerOpt IsNot Nothing Then
' Inserting base constructor call
Debug.Assert(Not hasMyBaseConstructorCall)
boundStatements.Add(constructorInitializerOpt)
ElseIf hasMyBaseConstructorCall Then
' Using existing constructor call -- it must be the first statement in the block
boundStatements.Add(blockStatements(0))
ElseIf Not constructorMethod.IsShared AndAlso containingType.IsValueType Then
' TODO: this can be skipped if we have equal number of initializers and fields
' assign all fields
' Me = Nothing
Dim syntax = block.Syntax
boundStatements.Add(
New BoundExpressionStatement(
syntax,
New BoundAssignmentOperator(
syntax,
New BoundValueTypeMeReference(syntax, containingType),
New BoundConversion(
syntax,
New BoundLiteral(syntax, ConstantValue.Null, Nothing),
ConversionKind.WideningNothingLiteral,
checked:=False,
explicitCastInCode:=False,
type:=containingType),
suppressObjectClone:=True,
type:=containingType)))
End If
' add hookups for Handles if needed
For Each member In containingType.GetMembers()
If member.Kind = SymbolKind.Method Then
Dim methodMember = DirectCast(member, MethodSymbol)
Dim handledEvents = methodMember.HandledEvents
If handledEvents.IsEmpty Then
Continue For
End If
' if method has definition and implementation parts
' their "Handles" should be merged.
If methodMember.IsPartial Then
Dim implementationPart = methodMember.PartialImplementationPart
If implementationPart IsNot Nothing Then
handledEvents = handledEvents.Concat(implementationPart.HandledEvents)
Else
' partial methods with no implementation do not handle anything
Continue For
End If
End If
For Each handledEvent In handledEvents
' it should be either Constructor or SharedConstructor
' if it is an instance constructor it should apply to all instance constructors.
If handledEvent.hookupMethod.MethodKind = constructorMethod.MethodKind Then
Dim eventSymbol = DirectCast(handledEvent.EventSymbol, EventSymbol)
Dim addHandlerMethod = eventSymbol.AddMethod
Dim delegateCreation = handledEvent.delegateCreation
Dim syntax = delegateCreation.Syntax
Dim receiver As BoundExpression = Nothing
If Not addHandlerMethod.IsShared Then
Dim meParam = constructorMethod.MeParameter
If TypeSymbol.Equals(addHandlerMethod.ContainingType, containingType, TypeCompareKind.ConsiderEverything) Then
receiver = New BoundMeReference(syntax, meParam.Type).MakeCompilerGenerated()
Else
'Dev10 always performs base call if event is in the base class.
'Even if Me/MyClass syntax was used. It seems to be somewhat of a bug
'that no-one cared about. For compat reasons we will do the same.
receiver = New BoundMyBaseReference(syntax, meParam.Type).MakeCompilerGenerated()
End If
End If
' Normally, we would synthesize lowered bound nodes, but we know that these nodes will
' be run through the LocalRewriter. Let the LocalRewriter handle the special code for
' WinRT events.
boundStatements.Add(
New BoundAddHandlerStatement(
syntax:=syntax,
eventAccess:=New BoundEventAccess(syntax, receiver, eventSymbol, eventSymbol.Type).MakeCompilerGenerated(),
handler:=delegateCreation).MakeCompilerGenerated())
End If
Next
End If
Next
' insert initializers AFTER implicit or explicit call to a base constructor
' and after Handles hookup if there were any
boundStatements.AddRange(initializerStatements)
' Add InitializeComponent call, if need to.
If Not constructorMethod.IsShared AndAlso compilationState.InitializeComponentOpt IsNot Nothing AndAlso constructorMethod.IsImplicitlyDeclared Then
boundStatements.Add(New BoundCall(constructorMethod.Syntax,
compilationState.InitializeComponentOpt, Nothing,
New BoundMeReference(constructorMethod.Syntax, compilationState.InitializeComponentOpt.ContainingType),
ImmutableArray(Of BoundExpression).Empty,
Nothing,
compilationState.InitializeComponentOpt.ReturnType).
MakeCompilerGenerated().ToStatement().MakeCompilerGenerated())
End If
' nothing was added
If boundStatements.Count = 0 Then
boundStatements.Free()
Return block
End If
' move the rest of the statements
For statementIndex = If(hasMyBaseConstructorCall, 1, 0) To blockStatements.Length - 1
boundStatements.Add(blockStatements(statementIndex))
Next
Return New BoundBlock(block.Syntax, block.StatementListSyntax, block.Locals, boundStatements.ToImmutableAndFree(), block.HasErrors)
End Function
Friend Function BuildScriptInitializerBody(
initializerMethod As SynthesizedInteractiveInitializerMethod,
processedInitializers As Binder.ProcessedFieldOrPropertyInitializers,
block As BoundBlock) As BoundBlock
Dim initializerStatements = RewriteInitializersAsStatements(initializerMethod, processedInitializers.BoundInitializers)
processedInitializers.InitializerStatements = initializerStatements
Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance()
boundStatements.AddRange(initializerStatements)
boundStatements.AddRange(block.Statements)
Return New BoundBlock(block.Syntax, block.StatementListSyntax, block.Locals, boundStatements.ToImmutableAndFree(), block.HasErrors)
End Function
''' <summary>
''' Rewrites GlobalStatementInitializers to ExpressionStatements and gets the initializers for fields and properties.
''' </summary>
''' <remarks>
''' Initializers for fields and properties cannot be rewritten to their final form at this place because they might need
''' to be rewritten to replace their placeholder expressions to the final locals or temporaries (e.g. in case of a field
''' declaration with "AsNew" and multiple variable names. The final rewriting will during local rewriting.
''' The statement list returned by this function can be copied into the initializer without reprocessing it.
''' </remarks>
Private Function RewriteInitializersAsStatements(
method As SynthesizedInteractiveInitializerMethod,
boundInitializers As ImmutableArray(Of BoundInitializer)) As ImmutableArray(Of BoundStatement)
Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance(boundInitializers.Length)
Dim submissionResultType = method.ResultType
Dim submissionResult As BoundExpression = Nothing
For Each initializer In boundInitializers
If submissionResultType IsNot Nothing AndAlso
initializer Is boundInitializers.Last AndAlso
initializer.Kind = BoundKind.GlobalStatementInitializer Then
Dim statement = DirectCast(initializer, BoundGlobalStatementInitializer).Statement
If statement.Kind = BoundKind.ExpressionStatement Then
Dim expr = DirectCast(statement, BoundExpressionStatement).Expression
Debug.Assert(expr.Type IsNot Nothing)
If expr.Type.SpecialType <> SpecialType.System_Void Then
submissionResult = expr
Continue For
End If
End If
End If
boundStatements.Add(RewriteInitializerAsStatement(initializer))
Next
If submissionResultType IsNot Nothing Then
If submissionResult Is Nothing Then
' Return Nothing if submission does not have a trailing expression.
submissionResult = New BoundLiteral(method.Syntax, ConstantValue.Nothing, submissionResultType)
End If
Debug.Assert(submissionResult.Type.SpecialType <> SpecialType.System_Void)
' The expression is converted to the submission result type when the initializer is bound.
boundStatements.Add(New BoundReturnStatement(submissionResult.Syntax, submissionResult, method.FunctionLocal, method.ExitLabel))
End If
Return boundStatements.ToImmutableAndFree()
End Function
Private Function RewriteInitializerAsStatement(initializer As BoundInitializer) As BoundStatement
Select Case initializer.Kind
Case BoundKind.FieldInitializer, BoundKind.PropertyInitializer
Return initializer
Case BoundKind.GlobalStatementInitializer
Return DirectCast(initializer, BoundGlobalStatementInitializer).Statement
Case Else
Throw ExceptionUtilities.UnexpectedValue(initializer.Kind)
End Select
End Function
''' <summary>
''' Determines if this constructor calls another constructor of the constructor's containing class.
''' </summary>
Friend Function HasExplicitMeConstructorCall(block As BoundBlock, container As TypeSymbol, <Out()> ByRef isMyBaseConstructorCall As Boolean) As Boolean
isMyBaseConstructorCall = False
If block.Statements.Any Then
Dim firstBoundStatement As BoundStatement = block.Statements.First()
' NOTE: it is assumed that an explicit constructor call from another constructor should
' NOT be nested into any statement lists and to be the first constructor of the
' block's statements; otherwise it would complicate this rewriting because we
' will have to insert field initializers right after constructor call
' NOTE: If in future some rewriters break this assumption, the insertion
' of initializers as well as the following code should be revised
If firstBoundStatement.Kind = BoundKind.ExpressionStatement Then
Dim expression = DirectCast(firstBoundStatement, BoundExpressionStatement).Expression
If expression.Kind = BoundKind.Call Then
Dim callExpression = DirectCast(expression, BoundCall)
Dim receiver = callExpression.ReceiverOpt
If receiver IsNot Nothing AndAlso receiver.IsInstanceReference Then
Dim methodSymbol = callExpression.Method
If methodSymbol.MethodKind = MethodKind.Constructor Then
isMyBaseConstructorCall = receiver.IsMyBaseReference
Return TypeSymbol.Equals(methodSymbol.ContainingType, container, TypeCompareKind.ConsiderEverything)
End If
End If
End If
End If
End If
Return False
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Turns the bound initializers into a list of bound assignment statements
''' </summary>
Friend Module InitializerRewriter
''' <summary>
''' Builds a constructor body.
''' </summary>
''' <remarks>
''' Lowers initializers to fields assignments if not lowered yet and the first statement of the body isn't
''' a call to another constructor of the containing class.
''' </remarks>
''' <returns>
''' Bound block including
''' - call to a base constructor
''' - field initializers and top-level code
''' - remaining constructor statements (empty for a submission)
''' </returns>
Friend Function BuildConstructorBody(
compilationState As TypeCompilationState,
constructorMethod As MethodSymbol,
constructorInitializerOpt As BoundStatement,
processedInitializers As Binder.ProcessedFieldOrPropertyInitializers,
block As BoundBlock) As BoundBlock
Dim hasMyBaseConstructorCall As Boolean = False
Dim containingType = constructorMethod.ContainingType
If HasExplicitMeConstructorCall(block, containingType, hasMyBaseConstructorCall) AndAlso Not hasMyBaseConstructorCall Then
Return block
End If
' rewrite initializers just once, statements will be reused when emitting all constructors with field initializers:
If processedInitializers.InitializerStatements.IsDefault Then
processedInitializers.InitializerStatements = processedInitializers.BoundInitializers.SelectAsArray(AddressOf RewriteInitializerAsStatement)
Debug.Assert(processedInitializers.BoundInitializers.Length = processedInitializers.InitializerStatements.Length)
End If
Dim initializerStatements = processedInitializers.InitializerStatements
Dim blockStatements As ImmutableArray(Of BoundStatement) = block.Statements
Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance()
If constructorInitializerOpt IsNot Nothing Then
' Inserting base constructor call
Debug.Assert(Not hasMyBaseConstructorCall)
boundStatements.Add(constructorInitializerOpt)
ElseIf hasMyBaseConstructorCall Then
' Using existing constructor call -- it must be the first statement in the block
boundStatements.Add(blockStatements(0))
ElseIf Not constructorMethod.IsShared AndAlso containingType.IsValueType Then
' TODO: this can be skipped if we have equal number of initializers and fields
' assign all fields
' Me = Nothing
Dim syntax = block.Syntax
boundStatements.Add(
New BoundExpressionStatement(
syntax,
New BoundAssignmentOperator(
syntax,
New BoundValueTypeMeReference(syntax, containingType),
New BoundConversion(
syntax,
New BoundLiteral(syntax, ConstantValue.Null, Nothing),
ConversionKind.WideningNothingLiteral,
checked:=False,
explicitCastInCode:=False,
type:=containingType),
suppressObjectClone:=True,
type:=containingType)))
End If
' add hookups for Handles if needed
For Each member In containingType.GetMembers()
If member.Kind = SymbolKind.Method Then
Dim methodMember = DirectCast(member, MethodSymbol)
Dim handledEvents = methodMember.HandledEvents
If handledEvents.IsEmpty Then
Continue For
End If
' if method has definition and implementation parts
' their "Handles" should be merged.
If methodMember.IsPartial Then
Dim implementationPart = methodMember.PartialImplementationPart
If implementationPart IsNot Nothing Then
handledEvents = handledEvents.Concat(implementationPart.HandledEvents)
Else
' partial methods with no implementation do not handle anything
Continue For
End If
End If
For Each handledEvent In handledEvents
' it should be either Constructor or SharedConstructor
' if it is an instance constructor it should apply to all instance constructors.
If handledEvent.hookupMethod.MethodKind = constructorMethod.MethodKind Then
Dim eventSymbol = DirectCast(handledEvent.EventSymbol, EventSymbol)
Dim addHandlerMethod = eventSymbol.AddMethod
Dim delegateCreation = handledEvent.delegateCreation
Dim syntax = delegateCreation.Syntax
Dim receiver As BoundExpression = Nothing
If Not addHandlerMethod.IsShared Then
Dim meParam = constructorMethod.MeParameter
If TypeSymbol.Equals(addHandlerMethod.ContainingType, containingType, TypeCompareKind.ConsiderEverything) Then
receiver = New BoundMeReference(syntax, meParam.Type).MakeCompilerGenerated()
Else
'Dev10 always performs base call if event is in the base class.
'Even if Me/MyClass syntax was used. It seems to be somewhat of a bug
'that no-one cared about. For compat reasons we will do the same.
receiver = New BoundMyBaseReference(syntax, meParam.Type).MakeCompilerGenerated()
End If
End If
' Normally, we would synthesize lowered bound nodes, but we know that these nodes will
' be run through the LocalRewriter. Let the LocalRewriter handle the special code for
' WinRT events.
boundStatements.Add(
New BoundAddHandlerStatement(
syntax:=syntax,
eventAccess:=New BoundEventAccess(syntax, receiver, eventSymbol, eventSymbol.Type).MakeCompilerGenerated(),
handler:=delegateCreation).MakeCompilerGenerated())
End If
Next
End If
Next
' insert initializers AFTER implicit or explicit call to a base constructor
' and after Handles hookup if there were any
boundStatements.AddRange(initializerStatements)
' Add InitializeComponent call, if need to.
If Not constructorMethod.IsShared AndAlso compilationState.InitializeComponentOpt IsNot Nothing AndAlso constructorMethod.IsImplicitlyDeclared Then
boundStatements.Add(New BoundCall(constructorMethod.Syntax,
compilationState.InitializeComponentOpt, Nothing,
New BoundMeReference(constructorMethod.Syntax, compilationState.InitializeComponentOpt.ContainingType),
ImmutableArray(Of BoundExpression).Empty,
Nothing,
compilationState.InitializeComponentOpt.ReturnType).
MakeCompilerGenerated().ToStatement().MakeCompilerGenerated())
End If
' nothing was added
If boundStatements.Count = 0 Then
boundStatements.Free()
Return block
End If
' move the rest of the statements
For statementIndex = If(hasMyBaseConstructorCall, 1, 0) To blockStatements.Length - 1
boundStatements.Add(blockStatements(statementIndex))
Next
Return New BoundBlock(block.Syntax, block.StatementListSyntax, block.Locals, boundStatements.ToImmutableAndFree(), block.HasErrors)
End Function
Friend Function BuildScriptInitializerBody(
initializerMethod As SynthesizedInteractiveInitializerMethod,
processedInitializers As Binder.ProcessedFieldOrPropertyInitializers,
block As BoundBlock) As BoundBlock
Dim initializerStatements = RewriteInitializersAsStatements(initializerMethod, processedInitializers.BoundInitializers)
processedInitializers.InitializerStatements = initializerStatements
Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance()
boundStatements.AddRange(initializerStatements)
boundStatements.AddRange(block.Statements)
Return New BoundBlock(block.Syntax, block.StatementListSyntax, block.Locals, boundStatements.ToImmutableAndFree(), block.HasErrors)
End Function
''' <summary>
''' Rewrites GlobalStatementInitializers to ExpressionStatements and gets the initializers for fields and properties.
''' </summary>
''' <remarks>
''' Initializers for fields and properties cannot be rewritten to their final form at this place because they might need
''' to be rewritten to replace their placeholder expressions to the final locals or temporaries (e.g. in case of a field
''' declaration with "AsNew" and multiple variable names. The final rewriting will during local rewriting.
''' The statement list returned by this function can be copied into the initializer without reprocessing it.
''' </remarks>
Private Function RewriteInitializersAsStatements(
method As SynthesizedInteractiveInitializerMethod,
boundInitializers As ImmutableArray(Of BoundInitializer)) As ImmutableArray(Of BoundStatement)
Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance(boundInitializers.Length)
Dim submissionResultType = method.ResultType
Dim submissionResult As BoundExpression = Nothing
For Each initializer In boundInitializers
If submissionResultType IsNot Nothing AndAlso
initializer Is boundInitializers.Last AndAlso
initializer.Kind = BoundKind.GlobalStatementInitializer Then
Dim statement = DirectCast(initializer, BoundGlobalStatementInitializer).Statement
If statement.Kind = BoundKind.ExpressionStatement Then
Dim expr = DirectCast(statement, BoundExpressionStatement).Expression
Debug.Assert(expr.Type IsNot Nothing)
If expr.Type.SpecialType <> SpecialType.System_Void Then
submissionResult = expr
Continue For
End If
End If
End If
boundStatements.Add(RewriteInitializerAsStatement(initializer))
Next
If submissionResultType IsNot Nothing Then
If submissionResult Is Nothing Then
' Return Nothing if submission does not have a trailing expression.
submissionResult = New BoundLiteral(method.Syntax, ConstantValue.Nothing, submissionResultType)
End If
Debug.Assert(submissionResult.Type.SpecialType <> SpecialType.System_Void)
' The expression is converted to the submission result type when the initializer is bound.
boundStatements.Add(New BoundReturnStatement(submissionResult.Syntax, submissionResult, method.FunctionLocal, method.ExitLabel))
End If
Return boundStatements.ToImmutableAndFree()
End Function
Private Function RewriteInitializerAsStatement(initializer As BoundInitializer) As BoundStatement
Select Case initializer.Kind
Case BoundKind.FieldInitializer, BoundKind.PropertyInitializer
Return initializer
Case BoundKind.GlobalStatementInitializer
Return DirectCast(initializer, BoundGlobalStatementInitializer).Statement
Case Else
Throw ExceptionUtilities.UnexpectedValue(initializer.Kind)
End Select
End Function
''' <summary>
''' Determines if this constructor calls another constructor of the constructor's containing class.
''' </summary>
Friend Function HasExplicitMeConstructorCall(block As BoundBlock, container As TypeSymbol, <Out()> ByRef isMyBaseConstructorCall As Boolean) As Boolean
isMyBaseConstructorCall = False
If block.Statements.Any Then
Dim firstBoundStatement As BoundStatement = block.Statements.First()
' NOTE: it is assumed that an explicit constructor call from another constructor should
' NOT be nested into any statement lists and to be the first constructor of the
' block's statements; otherwise it would complicate this rewriting because we
' will have to insert field initializers right after constructor call
' NOTE: If in future some rewriters break this assumption, the insertion
' of initializers as well as the following code should be revised
If firstBoundStatement.Kind = BoundKind.ExpressionStatement Then
Dim expression = DirectCast(firstBoundStatement, BoundExpressionStatement).Expression
If expression.Kind = BoundKind.Call Then
Dim callExpression = DirectCast(expression, BoundCall)
Dim receiver = callExpression.ReceiverOpt
If receiver IsNot Nothing AndAlso receiver.IsInstanceReference Then
Dim methodSymbol = callExpression.Method
If methodSymbol.MethodKind = MethodKind.Constructor Then
isMyBaseConstructorCall = receiver.IsMyBaseReference
Return TypeSymbol.Equals(methodSymbol.ContainingType, container, TypeCompareKind.ConsiderEverything)
End If
End If
End If
End If
End If
Return False
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Tools/ExternalAccess/Xamarin.Remote/Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote.csproj | <?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</RootNamespace>
<TargetFramework>net472</TargetFramework>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageId>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</PackageId>
<PackageDescription>
A supporting package for Xamarin:
https://github.com/xamarin/CodeAnalysis
</PackageDescription>
</PropertyGroup>
<ItemGroup>
<!--
⚠ ONLY XAMARIN ASSEMBLIES MAY BE ADDED HERE ⚠
-->
<InternalsVisibleTo Include="Xamarin.CodeAnalysis.Remote" Key="$(XamarinKey)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.CoreUtility" Version="$(MicrosoftVisualStudioCoreUtilityVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Text.Data" Version="$(MicrosoftVisualStudioTextDataVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Text.Logic" Version="$(MicrosoftVisualStudioTextLogicVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" />
<PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</RootNamespace>
<TargetFramework>net472</TargetFramework>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageId>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</PackageId>
<PackageDescription>
A supporting package for Xamarin:
https://github.com/xamarin/CodeAnalysis
</PackageDescription>
</PropertyGroup>
<ItemGroup>
<!--
⚠ ONLY XAMARIN ASSEMBLIES MAY BE ADDED HERE ⚠
-->
<InternalsVisibleTo Include="Xamarin.CodeAnalysis.Remote" Key="$(XamarinKey)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.CoreUtility" Version="$(MicrosoftVisualStudioCoreUtilityVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Text.Data" Version="$(MicrosoftVisualStudioTextDataVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Text.Logic" Version="$(MicrosoftVisualStudioTextLogicVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" />
<PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProviderFactory.cs | // Licensed to the .NET Foundation under one or more 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.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider.CodeStyle
{
internal class CommonCodeStyleSettingsProviderFactory : IWorkspaceSettingsProviderFactory<CodeStyleSetting>
{
private readonly Workspace _workspace;
public CommonCodeStyleSettingsProviderFactory(Workspace workspace) => _workspace = workspace;
public ISettingsProvider<CodeStyleSetting> GetForFile(string filePath)
=> new CommonCodeStyleSettingsProvider(filePath, new OptionUpdater(_workspace, filePath), _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 Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider.CodeStyle
{
internal class CommonCodeStyleSettingsProviderFactory : IWorkspaceSettingsProviderFactory<CodeStyleSetting>
{
private readonly Workspace _workspace;
public CommonCodeStyleSettingsProviderFactory(Workspace workspace) => _workspace = workspace;
public ISettingsProvider<CodeStyleSetting> GetForFile(string filePath)
=> new CommonCodeStyleSettingsProvider(filePath, new OptionUpdater(_workspace, filePath), _workspace);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/IntoKeywordRecommender.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 "Into" keyword.
''' </summary>
Friend Class IntoKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Into", VBFeaturesResources.Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
' "Into" for Group By is easy
If context.SyntaxTree.IsFollowingCompleteExpression(Of GroupByClauseSyntax)(
context.Position, context.TargetToken, Function(g) g.Keys.LastRangeExpression(), cancellationToken) Then
Return s_keywords
End If
' "Into" for Group Join is also easy
If context.SyntaxTree.IsFollowingCompleteExpression(Of GroupJoinClauseSyntax)(
context.Position, context.TargetToken, Function(g) g.JoinConditions.LastJoinKey(), cancellationToken) Then
Return s_keywords
End If
' "Into" for Aggregate is annoying, since it can be following after any number of arbitrary clauses
If context.IsQueryOperatorContext Then
Dim token = context.TargetToken.GetPreviousToken()
Dim aggregateQuery = token.GetAncestor(Of AggregateClauseSyntax)()
If aggregateQuery IsNot Nothing AndAlso (aggregateQuery.IntoKeyword.IsMissing OrElse aggregateQuery.IntoKeyword = token) Then
Return s_keywords
End If
End If
Return 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 "Into" keyword.
''' </summary>
Friend Class IntoKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Into", VBFeaturesResources.Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
' "Into" for Group By is easy
If context.SyntaxTree.IsFollowingCompleteExpression(Of GroupByClauseSyntax)(
context.Position, context.TargetToken, Function(g) g.Keys.LastRangeExpression(), cancellationToken) Then
Return s_keywords
End If
' "Into" for Group Join is also easy
If context.SyntaxTree.IsFollowingCompleteExpression(Of GroupJoinClauseSyntax)(
context.Position, context.TargetToken, Function(g) g.JoinConditions.LastJoinKey(), cancellationToken) Then
Return s_keywords
End If
' "Into" for Aggregate is annoying, since it can be following after any number of arbitrary clauses
If context.IsQueryOperatorContext Then
Dim token = context.TargetToken.GetPreviousToken()
Dim aggregateQuery = token.GetAncestor(Of AggregateClauseSyntax)()
If aggregateQuery IsNot Nothing AndAlso (aggregateQuery.IntoKeyword.IsMissing OrElse aggregateQuery.IntoKeyword = token) Then
Return s_keywords
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/CSharpTest2/Recommendations/AsyncKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class AsyncKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclaration1()
{
await VerifyKeywordAsync(@"class C
{
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclaration2()
{
await VerifyKeywordAsync(@"class C
{
public $$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclaration3()
{
await VerifyKeywordAsync(@"class C
{
$$ public void goo() { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface C
{
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclarationInGlobalStatement1()
{
const string text = @"$$";
await VerifyKeywordAsync(SourceCodeKind.Script, text);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclarationInGlobalStatement2()
{
const string text = @"public $$";
await VerifyKeywordAsync(SourceCodeKind.Script, text);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExpressionContext()
{
await VerifyKeywordAsync(@"class C
{
void goo()
{
goo($$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInParameter()
{
await VerifyAbsenceAsync(@"class C
{
void goo($$)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeLambda()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = $$ () => 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStaticLambda()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = $$ static () => 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticInLambda()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static $$ () => 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticInExpression()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDuplicateStaticInExpression()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static static $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticAsyncInExpression()
{
await VerifyAbsenceAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static async $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsyncStaticInExpression()
{
await VerifyAbsenceAsync(@"
class Program
{
static void Main(string[] args)
{
var z = async static $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttribute()
{
await VerifyAbsenceAsync(@"
class C
{
[$$
void M()
{
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeArgument()
{
await VerifyAbsenceAsync(@"
class C
{
[Attr($$
void M()
{
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStaticInExpression()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = $$ static
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotIfAlreadyAsync2()
{
await VerifyAbsenceAsync(@"
class Program
{
static void Main(string[] args)
{
var z = async $$ () => 2;
}
}");
}
[WorkItem(578061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578061")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInNamespace()
{
await VerifyAbsenceAsync(@"
namespace Goo
{
$$
}");
}
[WorkItem(578069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578069")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartialInNamespace()
{
await VerifyAbsenceAsync(@"
namespace Goo
{
partial $$
}");
}
[WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartialInClass()
{
await VerifyAbsenceAsync(@"
class Goo
{
partial $$
}");
}
[WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAttribute()
{
await VerifyKeywordAsync(@"
class Goo
{
[Attr] $$
}");
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task TestLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"unsafe $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction3(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"unsafe $$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction4(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction5()
{
await VerifyKeywordAsync(@"
class Goo
{
public void M(Action<int> a)
{
M(async () =>
{
$$
});
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction6(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"int $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction7(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class AsyncKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclaration1()
{
await VerifyKeywordAsync(@"class C
{
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclaration2()
{
await VerifyKeywordAsync(@"class C
{
public $$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclaration3()
{
await VerifyKeywordAsync(@"class C
{
$$ public void goo() { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface C
{
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclarationInGlobalStatement1()
{
const string text = @"$$";
await VerifyKeywordAsync(SourceCodeKind.Script, text);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMethodDeclarationInGlobalStatement2()
{
const string text = @"public $$";
await VerifyKeywordAsync(SourceCodeKind.Script, text);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestExpressionContext()
{
await VerifyKeywordAsync(@"class C
{
void goo()
{
goo($$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInParameter()
{
await VerifyAbsenceAsync(@"class C
{
void goo($$)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeLambda()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = $$ () => 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStaticLambda()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = $$ static () => 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticInLambda()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static $$ () => 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticInExpression()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDuplicateStaticInExpression()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static static $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticAsyncInExpression()
{
await VerifyAbsenceAsync(@"
class Program
{
static void Main(string[] args)
{
var z = static async $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsyncStaticInExpression()
{
await VerifyAbsenceAsync(@"
class Program
{
static void Main(string[] args)
{
var z = async static $$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttribute()
{
await VerifyAbsenceAsync(@"
class C
{
[$$
void M()
{
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeArgument()
{
await VerifyAbsenceAsync(@"
class C
{
[Attr($$
void M()
{
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStaticInExpression()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
var z = $$ static
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotIfAlreadyAsync2()
{
await VerifyAbsenceAsync(@"
class Program
{
static void Main(string[] args)
{
var z = async $$ () => 2;
}
}");
}
[WorkItem(578061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578061")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInNamespace()
{
await VerifyAbsenceAsync(@"
namespace Goo
{
$$
}");
}
[WorkItem(578069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578069")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartialInNamespace()
{
await VerifyAbsenceAsync(@"
namespace Goo
{
partial $$
}");
}
[WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartialInClass()
{
await VerifyAbsenceAsync(@"
class Goo
{
partial $$
}");
}
[WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAttribute()
{
await VerifyKeywordAsync(@"
class Goo
{
[Attr] $$
}");
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task TestLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"unsafe $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction3(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"unsafe $$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction4(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction5()
{
await VerifyKeywordAsync(@"
class Goo
{
public void M(Action<int> a)
{
M(async () =>
{
$$
});
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction6(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"int $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory]
[CombinatorialData]
[WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalFunction7(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.SymbolKeyReader.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private abstract class Reader<TStringResult> : IDisposable where TStringResult : class
{
protected const char OpenParenChar = '(';
protected const char CloseParenChar = ')';
protected const char SpaceChar = ' ';
protected const char DoubleQuoteChar = '"';
private readonly ReadFunction<TStringResult?> _readString;
private readonly ReadFunction<bool> _readBoolean;
private readonly ReadFunction<RefKind> _readRefKind;
protected string Data { get; private set; }
public CancellationToken CancellationToken { get; private set; }
public int Position;
public Reader()
{
_readString = ReadString;
_readBoolean = ReadBoolean;
_readRefKind = ReadRefKind;
Data = null!;
}
protected virtual void Initialize(string data, CancellationToken cancellationToken)
{
Data = data;
CancellationToken = cancellationToken;
Position = 0;
}
public virtual void Dispose()
{
Data = null!;
CancellationToken = default;
}
protected char Eat(SymbolKeyType type)
=> Eat((char)type);
protected char Eat(char c)
{
Debug.Assert(Data[Position] == c);
Position++;
return c;
}
protected void EatCloseParen()
=> Eat(CloseParenChar);
protected void EatOpenParen()
=> Eat(OpenParenChar);
public int ReadInteger()
{
EatSpace();
return ReadIntegerRaw_DoNotCallDirectly();
}
public int ReadFormatVersion()
=> ReadIntegerRaw_DoNotCallDirectly();
private int ReadIntegerRaw_DoNotCallDirectly()
{
Debug.Assert(char.IsNumber(Data[Position]));
var value = 0;
var start = Position;
while (char.IsNumber(Data[Position]))
{
var digit = Data[Position] - '0';
value *= 10;
value += digit;
Position++;
}
Debug.Assert(start != Position);
return value;
}
protected char EatSpace()
=> Eat(SpaceChar);
public bool ReadBoolean()
=> ReadBoolean(out _);
public bool ReadBoolean(out string? failureReason)
{
failureReason = null;
var val = ReadInteger();
Debug.Assert(val == 0 || val == 1);
return val == 1;
}
public TStringResult? ReadString()
=> ReadString(out _);
public TStringResult? ReadString(out string? failureReason)
{
failureReason = null;
EatSpace();
return ReadStringNoSpace();
}
protected TStringResult? ReadStringNoSpace()
{
if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
{
Eat(SymbolKeyType.Null);
return CreateNullForString();
}
EatDoubleQuote();
var start = Position;
var hasEmbeddedQuote = false;
while (true)
{
if (Data[Position] != DoubleQuoteChar)
{
Position++;
continue;
}
// We have a quote. See if it's the final quote, or if it's an escaped
// embedded quote.
if (Data[Position + 1] == DoubleQuoteChar)
{
hasEmbeddedQuote = true;
Position += 2;
continue;
}
break;
}
var end = Position;
EatDoubleQuote();
var result = CreateResultForString(start, end, hasEmbeddedQuote);
return result;
}
protected abstract TStringResult? CreateResultForString(int start, int end, bool hasEmbeddedQuote);
protected abstract TStringResult? CreateNullForString();
private void EatDoubleQuote()
=> Eat(DoubleQuoteChar);
public PooledArrayBuilder<TStringResult?> ReadStringArray()
=> ReadArray(_readString, out _);
public PooledArrayBuilder<bool> ReadBooleanArray()
=> ReadArray(_readBoolean, out _);
public PooledArrayBuilder<RefKind> ReadRefKindArray()
=> ReadArray(_readRefKind, out _);
public PooledArrayBuilder<T> ReadArray<T>(ReadFunction<T> readFunction, out string? failureReason)
{
var builder = PooledArrayBuilder<T>.GetInstance();
EatSpace();
Debug.Assert((SymbolKeyType)Data[Position] != SymbolKeyType.Null);
EatOpenParen();
Eat(SymbolKeyType.Array);
string? totalFailureReason = null;
var length = ReadInteger();
for (var i = 0; i < length; i++)
{
CancellationToken.ThrowIfCancellationRequested();
builder.Builder.Add(readFunction(out var elementFailureReason));
if (elementFailureReason != null)
{
var reason = $"element {i} failed {elementFailureReason}";
totalFailureReason = totalFailureReason == null
? $"({reason})"
: $"({totalFailureReason} -> {reason})";
}
}
EatCloseParen();
failureReason = totalFailureReason;
return builder;
}
public RefKind ReadRefKind()
=> ReadRefKind(out _);
public RefKind ReadRefKind(out string? failureReason)
{
failureReason = null;
return (RefKind)ReadInteger();
}
}
private class RemoveAssemblySymbolKeysReader : Reader<object>
{
private readonly StringBuilder _builder = new();
private bool _skipString = false;
public RemoveAssemblySymbolKeysReader()
{
}
public void Initialize(string data)
=> base.Initialize(data, CancellationToken.None);
public string RemoveAssemblySymbolKeys()
{
while (Position < Data.Length)
{
var ch = Data[Position];
if (ch == OpenParenChar)
{
_builder.Append(Eat(OpenParenChar));
var type = (SymbolKeyType)Data[Position];
_builder.Append(Eat(type));
if (type == SymbolKeyType.Assembly)
{
Debug.Assert(_skipString == false);
_skipString = true;
ReadString();
Debug.Assert(_skipString == true);
_skipString = false;
}
}
else if (Data[Position] == DoubleQuoteChar)
{
ReadStringNoSpace();
}
else
{
// All other characters we pass along directly to the string builder.
_builder.Append(Eat(ch));
}
}
return _builder.ToString();
}
protected override object? CreateResultForString(int start, int end, bool hasEmbeddedQuote)
{
// 'start' is right after the open quote, and 'end' is right before the close quote.
// However, we want to include both quotes in the result.
_builder.Append(DoubleQuoteChar);
if (!_skipString)
{
for (var i = start; i < end; i++)
{
_builder.Append(Data[i]);
}
}
_builder.Append(DoubleQuoteChar);
return null;
}
protected override object? CreateNullForString()
=> null;
}
private delegate T ReadFunction<T>(out string? failureReason);
private class SymbolKeyReader : Reader<string>
{
private static readonly ObjectPool<SymbolKeyReader> s_readerPool = SharedPools.Default<SymbolKeyReader>();
private readonly Dictionary<int, SymbolKeyResolution> _idToResult = new();
private readonly ReadFunction<SymbolKeyResolution> _readSymbolKey;
private readonly ReadFunction<Location?> _readLocation;
public Compilation Compilation { get; private set; }
public bool IgnoreAssemblyKey { get; private set; }
public SymbolEquivalenceComparer Comparer { get; private set; }
private readonly List<IMethodSymbol?> _methodSymbolStack = new();
public SymbolKeyReader()
{
_readSymbolKey = ReadSymbolKey;
_readLocation = ReadLocation;
Compilation = null!;
Comparer = null!;
}
public override void Dispose()
{
base.Dispose();
_idToResult.Clear();
Compilation = null!;
IgnoreAssemblyKey = false;
Comparer = null!;
_methodSymbolStack.Clear();
// Place us back in the pool for future use.
s_readerPool.Free(this);
}
public static SymbolKeyReader GetReader(
string data, Compilation compilation,
bool ignoreAssemblyKey,
CancellationToken cancellationToken)
{
var reader = s_readerPool.Allocate();
reader.Initialize(data, compilation, ignoreAssemblyKey, cancellationToken);
return reader;
}
private void Initialize(
string data,
Compilation compilation,
bool ignoreAssemblyKey,
CancellationToken cancellationToken)
{
base.Initialize(data, cancellationToken);
Compilation = compilation;
IgnoreAssemblyKey = ignoreAssemblyKey;
Comparer = ignoreAssemblyKey
? SymbolEquivalenceComparer.IgnoreAssembliesInstance
: SymbolEquivalenceComparer.Instance;
}
internal bool ParameterTypesMatch(
ImmutableArray<IParameterSymbol> parameters,
PooledArrayBuilder<ITypeSymbol> originalParameterTypes)
{
if (originalParameterTypes.IsDefault || parameters.Length != originalParameterTypes.Count)
{
return false;
}
// We are checking parameters for equality, if they refer to method type parameters,
// then we don't want to recurse through the method (which would then recurse right
// back into the parameters). So we use a signature type comparer as it will properly
// compare method type parameters by ordinal.
var signatureComparer = Comparer.SignatureTypeEquivalenceComparer;
for (var i = 0; i < originalParameterTypes.Count; i++)
{
if (!signatureComparer.Equals(originalParameterTypes[i], parameters[i].Type))
{
return false;
}
}
return true;
}
public void PushMethod(IMethodSymbol? method)
=> _methodSymbolStack.Add(method);
public void PopMethod(IMethodSymbol? method)
{
Contract.ThrowIfTrue(_methodSymbolStack.Count == 0);
Contract.ThrowIfFalse(Equals(method, _methodSymbolStack[_methodSymbolStack.Count - 1]));
_methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1);
}
public IMethodSymbol? ResolveMethod(int index)
=> _methodSymbolStack[index];
internal SyntaxTree? GetSyntaxTree(string filePath)
{
foreach (var tree in this.Compilation.SyntaxTrees)
{
if (tree.FilePath == filePath)
{
return tree;
}
}
return null;
}
#region Symbols
public SymbolKeyResolution ReadSymbolKey(out string? failureReason)
{
CancellationToken.ThrowIfCancellationRequested();
EatSpace();
var type = (SymbolKeyType)Data[Position];
if (type == SymbolKeyType.Null)
{
Eat(type);
failureReason = null;
return default;
}
EatOpenParen();
SymbolKeyResolution result;
type = (SymbolKeyType)Data[Position];
Eat(type);
if (type == SymbolKeyType.Reference)
{
var id = ReadInteger();
result = _idToResult[id];
failureReason = null;
}
else
{
result = ReadWorker(type, out failureReason);
var id = ReadInteger();
_idToResult[id] = result;
}
EatCloseParen();
return result;
}
private SymbolKeyResolution ReadWorker(SymbolKeyType type, out string? failureReason)
=> type switch
{
SymbolKeyType.Alias => AliasSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.BodyLevel => BodyLevelSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ConstructedMethod => ConstructedMethodSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.NamedType => NamedTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ErrorType => ErrorTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Field => FieldSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.FunctionPointer => FunctionPointerTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.DynamicType => DynamicTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Method => MethodSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Namespace => NamespaceSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.PointerType => PointerTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Parameter => ParameterSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Property => PropertySymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ArrayType => ArrayTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Assembly => AssemblySymbolKey.Resolve(this, out failureReason),
SymbolKeyType.TupleType => TupleTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Module => ModuleSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Event => EventSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ReducedExtensionMethod => ReducedExtensionMethodSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.TypeParameter => TypeParameterSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.AnonymousType => AnonymousTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.AnonymousFunctionOrDelegate => AnonymousFunctionOrDelegateSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.TypeParameterOrdinal => TypeParameterOrdinalSymbolKey.Resolve(this, out failureReason),
_ => throw new NotImplementedException(),
};
/// <summary>
/// Reads an array of symbols out from the key. Note: the number of symbols returned
/// will either be the same as the original amount written, or <c>default</c> will be
/// returned. It will never be less or more. <c>default</c> will be returned if any
/// elements could not be resolved to the requested <typeparamref name="TSymbol"/> type
/// in the provided <see cref="SymbolKeyReader.Compilation"/>.
///
/// Callers should <see cref="IDisposable.Dispose"/> the instance returned. No check is
/// necessary if <c>default</c> was returned before calling <see cref="IDisposable.Dispose"/>
/// </summary>
public PooledArrayBuilder<TSymbol> ReadSymbolKeyArray<TSymbol>(out string? failureReason) where TSymbol : ISymbol
{
using var resolutions = ReadArray(_readSymbolKey, out var elementsFailureReason);
if (elementsFailureReason != null)
{
failureReason = elementsFailureReason;
return default;
}
var result = PooledArrayBuilder<TSymbol>.GetInstance();
foreach (var resolution in resolutions)
{
if (resolution.GetAnySymbol() is TSymbol castedSymbol)
{
result.AddIfNotNull(castedSymbol);
}
else
{
result.Dispose();
failureReason = $"({nameof(ReadSymbolKeyArray)} incorrect type for element)";
return default;
}
}
failureReason = null;
return result;
}
#endregion
#region Strings
protected override string CreateResultForString(int start, int end, bool hasEmbeddedQuote)
{
var substring = Data.Substring(start, end - start);
var result = hasEmbeddedQuote
? substring.Replace("\"\"", "\"")
: substring;
return result;
}
protected override string? CreateNullForString()
=> null;
#endregion
#region Locations
public Location? ReadLocation(out string? failureReason)
{
EatSpace();
if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
{
Eat(SymbolKeyType.Null);
failureReason = null;
return null;
}
var kind = (LocationKind)ReadInteger();
if (kind == LocationKind.None)
{
failureReason = null;
return Location.None;
}
else if (kind == LocationKind.SourceFile)
{
var filePath = ReadString();
var start = ReadInteger();
var length = ReadInteger();
if (filePath == null)
{
failureReason = $"({nameof(ReadLocation)} failed -> '{nameof(filePath)}' came back null)";
return null;
}
var syntaxTree = GetSyntaxTree(filePath);
if (syntaxTree == null)
{
failureReason = $"({nameof(ReadLocation)} failed -> '{filePath}' not in compilation)";
return null;
}
failureReason = null;
return Location.Create(syntaxTree, new TextSpan(start, length));
}
else if (kind == LocationKind.MetadataFile)
{
var assemblyResolution = ReadSymbolKey(out var assemblyFailureReason);
var moduleName = ReadString();
if (assemblyFailureReason != null)
{
failureReason = $"{nameof(ReadLocation)} {nameof(assemblyResolution)} failed -> " + assemblyFailureReason;
return Location.None;
}
if (moduleName == null)
{
failureReason = $"({nameof(ReadLocation)} failed -> '{nameof(moduleName)}' came back null)";
return null;
}
// We may be resolving in a compilation where we don't have a module
// with this name. In that case, just map this location to none.
if (assemblyResolution.GetAnySymbol() is IAssemblySymbol assembly)
{
var module = GetModule(assembly.Modules, moduleName);
if (module != null)
{
var location = module.Locations.FirstOrDefault();
if (location != null)
{
failureReason = null;
return location;
}
}
}
failureReason = null;
return Location.None;
}
else
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
public SymbolKeyResolution? ResolveLocation(Location location)
{
if (location.SourceTree != null)
{
var node = location.FindNode(findInsideTrivia: true, getInnermostNodeForTie: true, CancellationToken);
var semanticModel = Compilation.GetSemanticModel(location.SourceTree);
var symbol = semanticModel.GetDeclaredSymbol(node, CancellationToken);
if (symbol != null)
return new SymbolKeyResolution(symbol);
var info = semanticModel.GetSymbolInfo(node, CancellationToken);
if (info.Symbol != null)
return new SymbolKeyResolution(info.Symbol);
if (info.CandidateSymbols.Length > 0)
return new SymbolKeyResolution(info.CandidateSymbols, info.CandidateReason);
}
return null;
}
private static IModuleSymbol? GetModule(IEnumerable<IModuleSymbol> modules, string moduleName)
{
foreach (var module in modules)
{
if (module.MetadataName == moduleName)
{
return module;
}
}
return null;
}
public PooledArrayBuilder<Location?> ReadLocationArray(out string? failureReason)
=> ReadArray(_readLocation, out failureReason);
#endregion
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private abstract class Reader<TStringResult> : IDisposable where TStringResult : class
{
protected const char OpenParenChar = '(';
protected const char CloseParenChar = ')';
protected const char SpaceChar = ' ';
protected const char DoubleQuoteChar = '"';
private readonly ReadFunction<TStringResult?> _readString;
private readonly ReadFunction<bool> _readBoolean;
private readonly ReadFunction<RefKind> _readRefKind;
protected string Data { get; private set; }
public CancellationToken CancellationToken { get; private set; }
public int Position;
public Reader()
{
_readString = ReadString;
_readBoolean = ReadBoolean;
_readRefKind = ReadRefKind;
Data = null!;
}
protected virtual void Initialize(string data, CancellationToken cancellationToken)
{
Data = data;
CancellationToken = cancellationToken;
Position = 0;
}
public virtual void Dispose()
{
Data = null!;
CancellationToken = default;
}
protected char Eat(SymbolKeyType type)
=> Eat((char)type);
protected char Eat(char c)
{
Debug.Assert(Data[Position] == c);
Position++;
return c;
}
protected void EatCloseParen()
=> Eat(CloseParenChar);
protected void EatOpenParen()
=> Eat(OpenParenChar);
public int ReadInteger()
{
EatSpace();
return ReadIntegerRaw_DoNotCallDirectly();
}
public int ReadFormatVersion()
=> ReadIntegerRaw_DoNotCallDirectly();
private int ReadIntegerRaw_DoNotCallDirectly()
{
Debug.Assert(char.IsNumber(Data[Position]));
var value = 0;
var start = Position;
while (char.IsNumber(Data[Position]))
{
var digit = Data[Position] - '0';
value *= 10;
value += digit;
Position++;
}
Debug.Assert(start != Position);
return value;
}
protected char EatSpace()
=> Eat(SpaceChar);
public bool ReadBoolean()
=> ReadBoolean(out _);
public bool ReadBoolean(out string? failureReason)
{
failureReason = null;
var val = ReadInteger();
Debug.Assert(val == 0 || val == 1);
return val == 1;
}
public TStringResult? ReadString()
=> ReadString(out _);
public TStringResult? ReadString(out string? failureReason)
{
failureReason = null;
EatSpace();
return ReadStringNoSpace();
}
protected TStringResult? ReadStringNoSpace()
{
if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
{
Eat(SymbolKeyType.Null);
return CreateNullForString();
}
EatDoubleQuote();
var start = Position;
var hasEmbeddedQuote = false;
while (true)
{
if (Data[Position] != DoubleQuoteChar)
{
Position++;
continue;
}
// We have a quote. See if it's the final quote, or if it's an escaped
// embedded quote.
if (Data[Position + 1] == DoubleQuoteChar)
{
hasEmbeddedQuote = true;
Position += 2;
continue;
}
break;
}
var end = Position;
EatDoubleQuote();
var result = CreateResultForString(start, end, hasEmbeddedQuote);
return result;
}
protected abstract TStringResult? CreateResultForString(int start, int end, bool hasEmbeddedQuote);
protected abstract TStringResult? CreateNullForString();
private void EatDoubleQuote()
=> Eat(DoubleQuoteChar);
public PooledArrayBuilder<TStringResult?> ReadStringArray()
=> ReadArray(_readString, out _);
public PooledArrayBuilder<bool> ReadBooleanArray()
=> ReadArray(_readBoolean, out _);
public PooledArrayBuilder<RefKind> ReadRefKindArray()
=> ReadArray(_readRefKind, out _);
public PooledArrayBuilder<T> ReadArray<T>(ReadFunction<T> readFunction, out string? failureReason)
{
var builder = PooledArrayBuilder<T>.GetInstance();
EatSpace();
Debug.Assert((SymbolKeyType)Data[Position] != SymbolKeyType.Null);
EatOpenParen();
Eat(SymbolKeyType.Array);
string? totalFailureReason = null;
var length = ReadInteger();
for (var i = 0; i < length; i++)
{
CancellationToken.ThrowIfCancellationRequested();
builder.Builder.Add(readFunction(out var elementFailureReason));
if (elementFailureReason != null)
{
var reason = $"element {i} failed {elementFailureReason}";
totalFailureReason = totalFailureReason == null
? $"({reason})"
: $"({totalFailureReason} -> {reason})";
}
}
EatCloseParen();
failureReason = totalFailureReason;
return builder;
}
public RefKind ReadRefKind()
=> ReadRefKind(out _);
public RefKind ReadRefKind(out string? failureReason)
{
failureReason = null;
return (RefKind)ReadInteger();
}
}
private class RemoveAssemblySymbolKeysReader : Reader<object>
{
private readonly StringBuilder _builder = new();
private bool _skipString = false;
public RemoveAssemblySymbolKeysReader()
{
}
public void Initialize(string data)
=> base.Initialize(data, CancellationToken.None);
public string RemoveAssemblySymbolKeys()
{
while (Position < Data.Length)
{
var ch = Data[Position];
if (ch == OpenParenChar)
{
_builder.Append(Eat(OpenParenChar));
var type = (SymbolKeyType)Data[Position];
_builder.Append(Eat(type));
if (type == SymbolKeyType.Assembly)
{
Debug.Assert(_skipString == false);
_skipString = true;
ReadString();
Debug.Assert(_skipString == true);
_skipString = false;
}
}
else if (Data[Position] == DoubleQuoteChar)
{
ReadStringNoSpace();
}
else
{
// All other characters we pass along directly to the string builder.
_builder.Append(Eat(ch));
}
}
return _builder.ToString();
}
protected override object? CreateResultForString(int start, int end, bool hasEmbeddedQuote)
{
// 'start' is right after the open quote, and 'end' is right before the close quote.
// However, we want to include both quotes in the result.
_builder.Append(DoubleQuoteChar);
if (!_skipString)
{
for (var i = start; i < end; i++)
{
_builder.Append(Data[i]);
}
}
_builder.Append(DoubleQuoteChar);
return null;
}
protected override object? CreateNullForString()
=> null;
}
private delegate T ReadFunction<T>(out string? failureReason);
private class SymbolKeyReader : Reader<string>
{
private static readonly ObjectPool<SymbolKeyReader> s_readerPool = SharedPools.Default<SymbolKeyReader>();
private readonly Dictionary<int, SymbolKeyResolution> _idToResult = new();
private readonly ReadFunction<SymbolKeyResolution> _readSymbolKey;
private readonly ReadFunction<Location?> _readLocation;
public Compilation Compilation { get; private set; }
public bool IgnoreAssemblyKey { get; private set; }
public SymbolEquivalenceComparer Comparer { get; private set; }
private readonly List<IMethodSymbol?> _methodSymbolStack = new();
public SymbolKeyReader()
{
_readSymbolKey = ReadSymbolKey;
_readLocation = ReadLocation;
Compilation = null!;
Comparer = null!;
}
public override void Dispose()
{
base.Dispose();
_idToResult.Clear();
Compilation = null!;
IgnoreAssemblyKey = false;
Comparer = null!;
_methodSymbolStack.Clear();
// Place us back in the pool for future use.
s_readerPool.Free(this);
}
public static SymbolKeyReader GetReader(
string data, Compilation compilation,
bool ignoreAssemblyKey,
CancellationToken cancellationToken)
{
var reader = s_readerPool.Allocate();
reader.Initialize(data, compilation, ignoreAssemblyKey, cancellationToken);
return reader;
}
private void Initialize(
string data,
Compilation compilation,
bool ignoreAssemblyKey,
CancellationToken cancellationToken)
{
base.Initialize(data, cancellationToken);
Compilation = compilation;
IgnoreAssemblyKey = ignoreAssemblyKey;
Comparer = ignoreAssemblyKey
? SymbolEquivalenceComparer.IgnoreAssembliesInstance
: SymbolEquivalenceComparer.Instance;
}
internal bool ParameterTypesMatch(
ImmutableArray<IParameterSymbol> parameters,
PooledArrayBuilder<ITypeSymbol> originalParameterTypes)
{
if (originalParameterTypes.IsDefault || parameters.Length != originalParameterTypes.Count)
{
return false;
}
// We are checking parameters for equality, if they refer to method type parameters,
// then we don't want to recurse through the method (which would then recurse right
// back into the parameters). So we use a signature type comparer as it will properly
// compare method type parameters by ordinal.
var signatureComparer = Comparer.SignatureTypeEquivalenceComparer;
for (var i = 0; i < originalParameterTypes.Count; i++)
{
if (!signatureComparer.Equals(originalParameterTypes[i], parameters[i].Type))
{
return false;
}
}
return true;
}
public void PushMethod(IMethodSymbol? method)
=> _methodSymbolStack.Add(method);
public void PopMethod(IMethodSymbol? method)
{
Contract.ThrowIfTrue(_methodSymbolStack.Count == 0);
Contract.ThrowIfFalse(Equals(method, _methodSymbolStack[_methodSymbolStack.Count - 1]));
_methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1);
}
public IMethodSymbol? ResolveMethod(int index)
=> _methodSymbolStack[index];
internal SyntaxTree? GetSyntaxTree(string filePath)
{
foreach (var tree in this.Compilation.SyntaxTrees)
{
if (tree.FilePath == filePath)
{
return tree;
}
}
return null;
}
#region Symbols
public SymbolKeyResolution ReadSymbolKey(out string? failureReason)
{
CancellationToken.ThrowIfCancellationRequested();
EatSpace();
var type = (SymbolKeyType)Data[Position];
if (type == SymbolKeyType.Null)
{
Eat(type);
failureReason = null;
return default;
}
EatOpenParen();
SymbolKeyResolution result;
type = (SymbolKeyType)Data[Position];
Eat(type);
if (type == SymbolKeyType.Reference)
{
var id = ReadInteger();
result = _idToResult[id];
failureReason = null;
}
else
{
result = ReadWorker(type, out failureReason);
var id = ReadInteger();
_idToResult[id] = result;
}
EatCloseParen();
return result;
}
private SymbolKeyResolution ReadWorker(SymbolKeyType type, out string? failureReason)
=> type switch
{
SymbolKeyType.Alias => AliasSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.BodyLevel => BodyLevelSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ConstructedMethod => ConstructedMethodSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.NamedType => NamedTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ErrorType => ErrorTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Field => FieldSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.FunctionPointer => FunctionPointerTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.DynamicType => DynamicTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Method => MethodSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Namespace => NamespaceSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.PointerType => PointerTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Parameter => ParameterSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Property => PropertySymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ArrayType => ArrayTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Assembly => AssemblySymbolKey.Resolve(this, out failureReason),
SymbolKeyType.TupleType => TupleTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Module => ModuleSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.Event => EventSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.ReducedExtensionMethod => ReducedExtensionMethodSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.TypeParameter => TypeParameterSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.AnonymousType => AnonymousTypeSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.AnonymousFunctionOrDelegate => AnonymousFunctionOrDelegateSymbolKey.Resolve(this, out failureReason),
SymbolKeyType.TypeParameterOrdinal => TypeParameterOrdinalSymbolKey.Resolve(this, out failureReason),
_ => throw new NotImplementedException(),
};
/// <summary>
/// Reads an array of symbols out from the key. Note: the number of symbols returned
/// will either be the same as the original amount written, or <c>default</c> will be
/// returned. It will never be less or more. <c>default</c> will be returned if any
/// elements could not be resolved to the requested <typeparamref name="TSymbol"/> type
/// in the provided <see cref="SymbolKeyReader.Compilation"/>.
///
/// Callers should <see cref="IDisposable.Dispose"/> the instance returned. No check is
/// necessary if <c>default</c> was returned before calling <see cref="IDisposable.Dispose"/>
/// </summary>
public PooledArrayBuilder<TSymbol> ReadSymbolKeyArray<TSymbol>(out string? failureReason) where TSymbol : ISymbol
{
using var resolutions = ReadArray(_readSymbolKey, out var elementsFailureReason);
if (elementsFailureReason != null)
{
failureReason = elementsFailureReason;
return default;
}
var result = PooledArrayBuilder<TSymbol>.GetInstance();
foreach (var resolution in resolutions)
{
if (resolution.GetAnySymbol() is TSymbol castedSymbol)
{
result.AddIfNotNull(castedSymbol);
}
else
{
result.Dispose();
failureReason = $"({nameof(ReadSymbolKeyArray)} incorrect type for element)";
return default;
}
}
failureReason = null;
return result;
}
#endregion
#region Strings
protected override string CreateResultForString(int start, int end, bool hasEmbeddedQuote)
{
var substring = Data.Substring(start, end - start);
var result = hasEmbeddedQuote
? substring.Replace("\"\"", "\"")
: substring;
return result;
}
protected override string? CreateNullForString()
=> null;
#endregion
#region Locations
public Location? ReadLocation(out string? failureReason)
{
EatSpace();
if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
{
Eat(SymbolKeyType.Null);
failureReason = null;
return null;
}
var kind = (LocationKind)ReadInteger();
if (kind == LocationKind.None)
{
failureReason = null;
return Location.None;
}
else if (kind == LocationKind.SourceFile)
{
var filePath = ReadString();
var start = ReadInteger();
var length = ReadInteger();
if (filePath == null)
{
failureReason = $"({nameof(ReadLocation)} failed -> '{nameof(filePath)}' came back null)";
return null;
}
var syntaxTree = GetSyntaxTree(filePath);
if (syntaxTree == null)
{
failureReason = $"({nameof(ReadLocation)} failed -> '{filePath}' not in compilation)";
return null;
}
failureReason = null;
return Location.Create(syntaxTree, new TextSpan(start, length));
}
else if (kind == LocationKind.MetadataFile)
{
var assemblyResolution = ReadSymbolKey(out var assemblyFailureReason);
var moduleName = ReadString();
if (assemblyFailureReason != null)
{
failureReason = $"{nameof(ReadLocation)} {nameof(assemblyResolution)} failed -> " + assemblyFailureReason;
return Location.None;
}
if (moduleName == null)
{
failureReason = $"({nameof(ReadLocation)} failed -> '{nameof(moduleName)}' came back null)";
return null;
}
// We may be resolving in a compilation where we don't have a module
// with this name. In that case, just map this location to none.
if (assemblyResolution.GetAnySymbol() is IAssemblySymbol assembly)
{
var module = GetModule(assembly.Modules, moduleName);
if (module != null)
{
var location = module.Locations.FirstOrDefault();
if (location != null)
{
failureReason = null;
return location;
}
}
}
failureReason = null;
return Location.None;
}
else
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
public SymbolKeyResolution? ResolveLocation(Location location)
{
if (location.SourceTree != null)
{
var node = location.FindNode(findInsideTrivia: true, getInnermostNodeForTie: true, CancellationToken);
var semanticModel = Compilation.GetSemanticModel(location.SourceTree);
var symbol = semanticModel.GetDeclaredSymbol(node, CancellationToken);
if (symbol != null)
return new SymbolKeyResolution(symbol);
var info = semanticModel.GetSymbolInfo(node, CancellationToken);
if (info.Symbol != null)
return new SymbolKeyResolution(info.Symbol);
if (info.CandidateSymbols.Length > 0)
return new SymbolKeyResolution(info.CandidateSymbols, info.CandidateReason);
}
return null;
}
private static IModuleSymbol? GetModule(IEnumerable<IModuleSymbol> modules, string moduleName)
{
foreach (var module in modules)
{
if (module.MetadataName == moduleName)
{
return module;
}
}
return null;
}
public PooledArrayBuilder<Location?> ReadLocationArray(out string? failureReason)
=> ReadArray(_readLocation, out failureReason);
#endregion
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/CSharpTest/FullyQualify/FullyQualifyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FullyQualify;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FullyQualify
{
public class FullyQualifyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public FullyQualifyTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpFullyQualifyCodeFixProvider());
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.IDictionary Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.Generic.IDictionary Method()
{
Goo();
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithNoArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.Generic.List Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithCorrectArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSmartTagDisplayText()
{
await TestSmartTagTextAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
"System.Collections.Generic.List");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithWrongArgs()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericInLocalDeclaration()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Goo()
{
[|List<int>|] a = new List<int>();
}
}",
@"class Class
{
void Goo()
{
System.Collections.Generic.List<int> a = new List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericItemType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System.Collections.Generic;
class Class
{
List<System.Int32> l;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateWithExistingUsings()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespaceWithUsings()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExistingUsing()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
count: 1);
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
System.Collections.IDictionary Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBound()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Class
{
[|String|] Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBoundGeneric()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnEnum()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Goo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"class Class
{
void Goo()
{
var a = A.Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnClassInheritance()
{
await TestInRegularAndScriptAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"class Class : A.Class2
{
}
namespace A
{
class Class2
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnImplementedInterface()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IGoo|]
{
}
namespace A
{
interface IGoo
{
}
}",
@"class Class : A.IGoo
{
}
namespace A
{
interface IGoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAllInBaseList()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IGoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"class Class : B.IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}");
await TestInRegularAndScriptAsync(
@"class Class : B.IGoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"class Class : B.IGoo, A.Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeUnexpanded()
{
await TestInRegularAndScriptAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"[System.Obsolete]
class Class
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeExpanded()
{
await TestInRegularAndScriptAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"[System.ObsoleteAttribute]
class Class
{
}");
}
[WorkItem(527360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExtensionMethods()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>() { 1, 2, 3 };
values.[|Where|](i => i > 1);
}
}");
}
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterNew()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Goo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"class Class
{
void Goo()
{
List<int> l;
l = new System.Collections.Generic.List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestArgumentsInMethodCall()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"class Class
{
void Test()
{
Console.WriteLine(System.DateTime.Today);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestCallSiteArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"class Class
{
void Test(System.DateTime dt)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestUsePartialClass()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"namespace A
{
public class Class
{
B.PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericClassInNestedNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
A.B.GenericClass<int> c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeStaticMethod()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
[|Math|].Sqrt();
}",
@"class Class
{
void Test()
{
System.Math.Sqrt();
}");
}
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}",
@"namespace A
{
class Class
{
B.C.Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSimpleNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*goo*/[|Int32|] i; } }",
@"class Class { void Test() { /*goo*/System.Int32 i; } }");
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*goo*/[|List<int>|] l; } }",
@"class Class { void Test() { /*goo*/System.Collections.Generic.List<int> l; } }");
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName()
{
await TestInRegularAndScriptAsync(
@"public class Program
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}",
@"public class Program
{
public class Inner
{
}
}
class Test
{
Program.Inner i;
}");
}
[WorkItem(26887, "https://github.com/dotnet/roslyn/issues/26887")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyUnboundIdentifier3()
{
await TestInRegularAndScriptAsync(
@"public class Program
{
public class Inner
{
}
}
class Test
{
public [|Inner|] Name
}",
@"public class Program
{
public class Inner
{
}
}
class Test
{
public Program.Inner Name
}");
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName_NotForGenericType()
{
await TestMissingInRegularAndScriptAsync(
@"class Program<T>
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}");
}
[WorkItem(538764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyThroughAlias()
{
await TestInRegularAndScriptAsync(
@"using Alias = System;
class C
{
[|Int32|] i;
}",
@"using Alias = System;
class C
{
Alias.Int32 i;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C.C c;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C c;
}",
index: 1);
}
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterAlias()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
System::[|Console|] :: WriteLine(""TEST"");
}
}");
}
[WorkItem(540942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnIncompleteStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.IO;
class C
{
static void Main(string[] args)
{
[|Path|] }
}");
}
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAssemblyAttribute()
{
await TestInRegularAndScriptAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project"")]");
}
[WorkItem(543388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAliasName()
{
await TestMissingInRegularAndScriptAsync(
@"using [|GIBBERISH|] = Goo.GIBBERISH;
class Program
{
static void Main(string[] args)
{
GIBBERISH x;
}
}
namespace Goo
{
public class GIBBERISH
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAttributeOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Runtime.InteropServices;
class M
{
[[|DllImport|]()]
static extern int? My();
}");
}
[WorkItem(544950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnAbstractConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"using System.IO;
class Program
{
static void Main(string[] args)
{
var s = new [|Stream|]();
}
}");
}
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttribute()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 2);
await TestInRegularAndScriptAsync(
input,
@"[ assembly : System.Runtime.InteropServices.Guid( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ");
}
[WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGeneratePropertyFromAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
[AttributeUsage(AttributeTargets.Class)]
class MyAttrAttribute : Attribute
{
}
[MyAttr(123, [|Version|] = 1)]
class D
{
}");
}
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task ShouldTriggerOnCS0308()
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestInRegularAndScriptAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<int> f;
}
}");
}
[WorkItem(947579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousTypeFix()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
class B
{
void M1()
{
[|var a = new A();|]
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}",
@"using n1;
using n2;
class B
{
void M1()
{
var a = new n1.A();
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}");
}
[WorkItem(995857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task NonPublicNamespaces()
{
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
System.Xaml
}
}");
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
MS.Internal.Xaml
}
}", index: 1);
}
[WorkItem(11071, "https://github.com/dotnet/roslyn/issues/11071")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousFixOrdering()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
[[|Inner|].C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}",
@"using n1;
using n2;
[n2.Inner.C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleTest()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|], string) Method()
{
Goo();
}
}",
@"class Class
{
(System.Collections.IDictionary, string) Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|] a, string) Method()
{
Goo();
}
}",
@"class Class
{
(System.Collections.IDictionary a, string) Method()
{
Goo();
}
}");
}
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
[WorkItem(18623, "https://github.com/dotnet/roslyn/issues/18623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestDoNotQualifyToTheSameTypeToFixWrongArity()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class Program : [|IReadOnlyCollection|]
{
}");
}
[WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression()
{
var code = @"
class C
{
private void GetEvaluationRuleNames()
{
[|IEnumerable|] < Int32 >
return ImmutableArray.CreateRange();
}
}";
await TestActionCountAsync(code, count: 1);
await TestInRegularAndScriptAsync(
code,
@"
class C
{
private void GetEvaluationRuleNames()
{
System.Collections.Generic.IEnumerable < Int32 >
return ImmutableArray.CreateRange();
}
}");
}
[WorkItem(49986, "https://github.com/dotnet/roslyn/issues/49986")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_Type()
{
await TestInRegularAndScriptAsync(
@"using [|Math|];
class Class
{
void Test()
{
Sqrt(1);
}",
@"using static System.Math;
class Class
{
void Test()
{
Sqrt(1);
}");
}
[WorkItem(49986, "https://github.com/dotnet/roslyn/issues/49986")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_Namespace()
{
await TestInRegularAndScriptAsync(
@"using [|Collections|];
class Class
{
void Test()
{
Sqrt(1);
}",
@"using System.Collections;
class Class
{
void Test()
{
Sqrt(1);
}");
}
[WorkItem(49986, "https://github.com/dotnet/roslyn/issues/49986")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_UsingStatic()
{
await TestInRegularAndScriptAsync(
@"using static [|Math|];
class Class
{
void Test()
{
Sqrt(1);
}",
@"using static System.Math;
class Class
{
void Test()
{
Sqrt(1);
}");
}
[WorkItem(51274, "https://github.com/dotnet/roslyn/issues/51274")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_UsingAlias()
{
await TestInRegularAndScriptAsync(
@"using M = [|Math|]",
@"using M = System.Math");
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableNeverSameProject()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
using System.ComponentModel;
namespace ProjectLib
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class Project
{
}
}
</Document>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
class Program
{
static void Main(string[] args)
{
Project p = new [|ProjectLib.Project()|];
}
}
";
await TestInRegularAndScript1Async(InitialWorkspace, ExpectedDocumentText);
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableNeverDifferentProject()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Never)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace);
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
class Program
{
static void Main(string[] args)
{
ProjectLib.Project p = new Project();
}
}
";
await TestInRegularAndScript1Async(InitialWorkspace, ExpectedDocumentText);
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(
options: Option(CompletionOptions.HideAdvancedMembers, true)));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FullyQualify;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FullyQualify
{
public class FullyQualifyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public FullyQualifyTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpFullyQualifyCodeFixProvider());
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.IDictionary Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.Generic.IDictionary Method()
{
Goo();
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithNoArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.Generic.List Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithCorrectArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSmartTagDisplayText()
{
await TestSmartTagTextAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
"System.Collections.Generic.List");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithWrongArgs()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericInLocalDeclaration()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Goo()
{
[|List<int>|] a = new List<int>();
}
}",
@"class Class
{
void Goo()
{
System.Collections.Generic.List<int> a = new List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericItemType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System.Collections.Generic;
class Class
{
List<System.Int32> l;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateWithExistingUsings()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespaceWithUsings()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Goo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExistingUsing()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
count: 1);
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
System.Collections.IDictionary Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBound()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Class
{
[|String|] Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBoundGeneric()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnEnum()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Goo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"class Class
{
void Goo()
{
var a = A.Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnClassInheritance()
{
await TestInRegularAndScriptAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"class Class : A.Class2
{
}
namespace A
{
class Class2
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnImplementedInterface()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IGoo|]
{
}
namespace A
{
interface IGoo
{
}
}",
@"class Class : A.IGoo
{
}
namespace A
{
interface IGoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAllInBaseList()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IGoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"class Class : B.IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}");
await TestInRegularAndScriptAsync(
@"class Class : B.IGoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"class Class : B.IGoo, A.Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeUnexpanded()
{
await TestInRegularAndScriptAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"[System.Obsolete]
class Class
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeExpanded()
{
await TestInRegularAndScriptAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"[System.ObsoleteAttribute]
class Class
{
}");
}
[WorkItem(527360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExtensionMethods()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>() { 1, 2, 3 };
values.[|Where|](i => i > 1);
}
}");
}
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterNew()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Goo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"class Class
{
void Goo()
{
List<int> l;
l = new System.Collections.Generic.List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestArgumentsInMethodCall()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"class Class
{
void Test()
{
Console.WriteLine(System.DateTime.Today);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestCallSiteArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"class Class
{
void Test(System.DateTime dt)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestUsePartialClass()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"namespace A
{
public class Class
{
B.PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericClassInNestedNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
A.B.GenericClass<int> c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeStaticMethod()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
[|Math|].Sqrt();
}",
@"class Class
{
void Test()
{
System.Math.Sqrt();
}");
}
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}",
@"namespace A
{
class Class
{
B.C.Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSimpleNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*goo*/[|Int32|] i; } }",
@"class Class { void Test() { /*goo*/System.Int32 i; } }");
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*goo*/[|List<int>|] l; } }",
@"class Class { void Test() { /*goo*/System.Collections.Generic.List<int> l; } }");
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName()
{
await TestInRegularAndScriptAsync(
@"public class Program
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}",
@"public class Program
{
public class Inner
{
}
}
class Test
{
Program.Inner i;
}");
}
[WorkItem(26887, "https://github.com/dotnet/roslyn/issues/26887")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyUnboundIdentifier3()
{
await TestInRegularAndScriptAsync(
@"public class Program
{
public class Inner
{
}
}
class Test
{
public [|Inner|] Name
}",
@"public class Program
{
public class Inner
{
}
}
class Test
{
public Program.Inner Name
}");
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName_NotForGenericType()
{
await TestMissingInRegularAndScriptAsync(
@"class Program<T>
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}");
}
[WorkItem(538764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyThroughAlias()
{
await TestInRegularAndScriptAsync(
@"using Alias = System;
class C
{
[|Int32|] i;
}",
@"using Alias = System;
class C
{
Alias.Int32 i;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C.C c;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C c;
}",
index: 1);
}
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterAlias()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
System::[|Console|] :: WriteLine(""TEST"");
}
}");
}
[WorkItem(540942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnIncompleteStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.IO;
class C
{
static void Main(string[] args)
{
[|Path|] }
}");
}
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAssemblyAttribute()
{
await TestInRegularAndScriptAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project"")]");
}
[WorkItem(543388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAliasName()
{
await TestMissingInRegularAndScriptAsync(
@"using [|GIBBERISH|] = Goo.GIBBERISH;
class Program
{
static void Main(string[] args)
{
GIBBERISH x;
}
}
namespace Goo
{
public class GIBBERISH
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAttributeOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Runtime.InteropServices;
class M
{
[[|DllImport|]()]
static extern int? My();
}");
}
[WorkItem(544950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnAbstractConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"using System.IO;
class Program
{
static void Main(string[] args)
{
var s = new [|Stream|]();
}
}");
}
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttribute()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 2);
await TestInRegularAndScriptAsync(
input,
@"[ assembly : System.Runtime.InteropServices.Guid( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ");
}
[WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGeneratePropertyFromAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
[AttributeUsage(AttributeTargets.Class)]
class MyAttrAttribute : Attribute
{
}
[MyAttr(123, [|Version|] = 1)]
class D
{
}");
}
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task ShouldTriggerOnCS0308()
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestInRegularAndScriptAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<int> f;
}
}");
}
[WorkItem(947579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousTypeFix()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
class B
{
void M1()
{
[|var a = new A();|]
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}",
@"using n1;
using n2;
class B
{
void M1()
{
var a = new n1.A();
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}");
}
[WorkItem(995857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task NonPublicNamespaces()
{
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
System.Xaml
}
}");
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
MS.Internal.Xaml
}
}", index: 1);
}
[WorkItem(11071, "https://github.com/dotnet/roslyn/issues/11071")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousFixOrdering()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
[[|Inner|].C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}",
@"using n1;
using n2;
[n2.Inner.C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleTest()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|], string) Method()
{
Goo();
}
}",
@"class Class
{
(System.Collections.IDictionary, string) Method()
{
Goo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|] a, string) Method()
{
Goo();
}
}",
@"class Class
{
(System.Collections.IDictionary a, string) Method()
{
Goo();
}
}");
}
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
[WorkItem(18623, "https://github.com/dotnet/roslyn/issues/18623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestDoNotQualifyToTheSameTypeToFixWrongArity()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class Program : [|IReadOnlyCollection|]
{
}");
}
[WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression()
{
var code = @"
class C
{
private void GetEvaluationRuleNames()
{
[|IEnumerable|] < Int32 >
return ImmutableArray.CreateRange();
}
}";
await TestActionCountAsync(code, count: 1);
await TestInRegularAndScriptAsync(
code,
@"
class C
{
private void GetEvaluationRuleNames()
{
System.Collections.Generic.IEnumerable < Int32 >
return ImmutableArray.CreateRange();
}
}");
}
[WorkItem(49986, "https://github.com/dotnet/roslyn/issues/49986")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_Type()
{
await TestInRegularAndScriptAsync(
@"using [|Math|];
class Class
{
void Test()
{
Sqrt(1);
}",
@"using static System.Math;
class Class
{
void Test()
{
Sqrt(1);
}");
}
[WorkItem(49986, "https://github.com/dotnet/roslyn/issues/49986")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_Namespace()
{
await TestInRegularAndScriptAsync(
@"using [|Collections|];
class Class
{
void Test()
{
Sqrt(1);
}",
@"using System.Collections;
class Class
{
void Test()
{
Sqrt(1);
}");
}
[WorkItem(49986, "https://github.com/dotnet/roslyn/issues/49986")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_UsingStatic()
{
await TestInRegularAndScriptAsync(
@"using static [|Math|];
class Class
{
void Test()
{
Sqrt(1);
}",
@"using static System.Math;
class Class
{
void Test()
{
Sqrt(1);
}");
}
[WorkItem(51274, "https://github.com/dotnet/roslyn/issues/51274")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestInUsingContext_UsingAlias()
{
await TestInRegularAndScriptAsync(
@"using M = [|Math|]",
@"using M = System.Math");
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableNeverSameProject()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
using System.ComponentModel;
namespace ProjectLib
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class Project
{
}
}
</Document>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
class Program
{
static void Main(string[] args)
{
Project p = new [|ProjectLib.Project()|];
}
}
";
await TestInRegularAndScript1Async(InitialWorkspace, ExpectedDocumentText);
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableNeverDifferentProject()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Never)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace);
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
class Program
{
static void Main(string[] args)
{
ProjectLib.Project p = new Project();
}
}
";
await TestInRegularAndScript1Async(InitialWorkspace, ExpectedDocumentText);
}
[Fact]
[WorkItem(54544, "https://github.com/dotnet/roslyn/issues/54544")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(
options: Option(CompletionOptions.HideAdvancedMembers, true)));
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/Core/Portable/Compilation/CommonModuleCompilationState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis
{
internal class CommonModuleCompilationState
{
private bool _frozen;
internal void Freeze()
{
Debug.Assert(!_frozen);
// make sure that values from all threads are visible:
Interlocked.MemoryBarrier();
_frozen = true;
}
internal bool Frozen
{
get { return _frozen; }
}
}
internal class ModuleCompilationState<TNamedTypeSymbol, TMethodSymbol> : CommonModuleCompilationState
where TNamedTypeSymbol : class, INamedTypeSymbolInternal
where TMethodSymbol : class, IMethodSymbolInternal
{
/// <summary>
/// Maps an async/iterator method to the synthesized state machine type that implements the method.
/// </summary>
private Dictionary<TMethodSymbol, TNamedTypeSymbol>? _lazyStateMachineTypes;
internal void SetStateMachineType(TMethodSymbol method, TNamedTypeSymbol stateMachineClass)
{
Debug.Assert(!Frozen);
if (_lazyStateMachineTypes == null)
{
Interlocked.CompareExchange(ref _lazyStateMachineTypes, new Dictionary<TMethodSymbol, TNamedTypeSymbol>(), null);
}
lock (_lazyStateMachineTypes)
{
_lazyStateMachineTypes.Add(method, stateMachineClass);
}
}
internal bool TryGetStateMachineType(TMethodSymbol method, [NotNullWhen(true)] out TNamedTypeSymbol? stateMachineType)
{
Debug.Assert(Frozen);
stateMachineType = null;
return _lazyStateMachineTypes != null && _lazyStateMachineTypes.TryGetValue(method, out stateMachineType);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis
{
internal class CommonModuleCompilationState
{
private bool _frozen;
internal void Freeze()
{
Debug.Assert(!_frozen);
// make sure that values from all threads are visible:
Interlocked.MemoryBarrier();
_frozen = true;
}
internal bool Frozen
{
get { return _frozen; }
}
}
internal class ModuleCompilationState<TNamedTypeSymbol, TMethodSymbol> : CommonModuleCompilationState
where TNamedTypeSymbol : class, INamedTypeSymbolInternal
where TMethodSymbol : class, IMethodSymbolInternal
{
/// <summary>
/// Maps an async/iterator method to the synthesized state machine type that implements the method.
/// </summary>
private Dictionary<TMethodSymbol, TNamedTypeSymbol>? _lazyStateMachineTypes;
internal void SetStateMachineType(TMethodSymbol method, TNamedTypeSymbol stateMachineClass)
{
Debug.Assert(!Frozen);
if (_lazyStateMachineTypes == null)
{
Interlocked.CompareExchange(ref _lazyStateMachineTypes, new Dictionary<TMethodSymbol, TNamedTypeSymbol>(), null);
}
lock (_lazyStateMachineTypes)
{
_lazyStateMachineTypes.Add(method, stateMachineClass);
}
}
internal bool TryGetStateMachineType(TMethodSymbol method, [NotNullWhen(true)] out TNamedTypeSymbol? stateMachineType)
{
Debug.Assert(Frozen);
stateMachineType = null;
return _lazyStateMachineTypes != null && _lazyStateMachineTypes.TryGetValue(method, out stateMachineType);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/Core.Wpf/Interactive/IResettableInteractiveEvaluator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Tasks;
using Microsoft.VisualStudio.InteractiveWindow;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal interface IResettableInteractiveEvaluator : IInteractiveEvaluator
{
InteractiveEvaluatorResetOptions ResetOptions { get; set; }
Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Tasks;
using Microsoft.VisualStudio.InteractiveWindow;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal interface IResettableInteractiveEvaluator : IInteractiveEvaluator
{
InteractiveEvaluatorResetOptions ResetOptions { get; set; }
Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableEntriesSnapshot.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Base implementation of ITableEntriesSnapshot
/// </summary>
internal abstract class AbstractTableEntriesSnapshot<TItem> : ITableEntriesSnapshot
where TItem : TableItem
{
// TODO : remove these once we move to new drop which contains API change from editor team
protected const string ProjectNames = StandardTableKeyNames.ProjectName + "s";
protected const string ProjectGuids = StandardTableKeyNames.ProjectGuid + "s";
private readonly int _version;
private readonly ImmutableArray<TItem> _items;
private ImmutableArray<ITrackingPoint> _trackingPoints;
protected AbstractTableEntriesSnapshot(int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints)
{
_version = version;
_items = items;
_trackingPoints = trackingPoints;
}
public abstract bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken);
public abstract bool TryGetValue(int index, string columnName, out object content);
public int VersionNumber
{
get
{
return _version;
}
}
public int Count
{
get
{
return _items.Length;
}
}
public int IndexOf(int index, ITableEntriesSnapshot newerSnapshot)
{
var item = GetItem(index);
if (item == null)
{
return -1;
}
if (!(newerSnapshot is AbstractTableEntriesSnapshot<TItem> ourSnapshot) || ourSnapshot.Count == 0)
{
// not ours, we don't know how to track index
return -1;
}
// quick path - this will deal with a case where we update data without any actual change
if (Count == ourSnapshot.Count)
{
var newItem = ourSnapshot.GetItem(index);
if (newItem != null && newItem.Equals(item))
{
return index;
}
}
// slow path.
for (var i = 0; i < ourSnapshot.Count; i++)
{
var newItem = ourSnapshot.GetItem(i);
if (item.EqualsIgnoringLocation(newItem))
{
return i;
}
}
// no similar item exist. table control itself will try to maintain selection
return -1;
}
public void StopTracking()
{
// remove tracking points
_trackingPoints = default;
}
public void Dispose()
=> StopTracking();
internal TItem GetItem(int index)
{
if (index < 0 || _items.Length <= index)
{
return null;
}
return _items[index];
}
protected LinePosition GetTrackingLineColumn(Document document, int index)
{
if (_trackingPoints.IsDefaultOrEmpty)
{
return LinePosition.Zero;
}
var trackingPoint = _trackingPoints[index];
if (!document.TryGetText(out var text))
{
return LinePosition.Zero;
}
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
return GetLinePosition(snapshot, trackingPoint);
}
var textBuffer = text.Container.TryGetTextBuffer();
if (textBuffer == null)
{
return LinePosition.Zero;
}
var currentSnapshot = textBuffer.CurrentSnapshot;
return GetLinePosition(currentSnapshot, trackingPoint);
}
private static LinePosition GetLinePosition(ITextSnapshot snapshot, ITrackingPoint trackingPoint)
{
var point = trackingPoint.GetPoint(snapshot);
var line = point.GetContainingLine();
return new LinePosition(line.LineNumber, point.Position - line.Start);
}
protected static bool TryNavigateTo(Workspace workspace, DocumentId documentId, LinePosition position, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
if (navigationService == null)
{
return false;
}
var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, previewTab)
.WithChangedOption(NavigationOptions.ActivateTab, activate);
return navigationService.TryNavigateToLineAndOffset(workspace, documentId, position.Line, position.Character, options, cancellationToken);
}
protected bool TryNavigateToItem(int index, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var item = GetItem(index);
var documentId = item?.DocumentId;
if (documentId == null)
{
return false;
}
var workspace = item.Workspace;
var solution = workspace.CurrentSolution;
var document = solution.GetDocument(documentId);
if (document == null)
{
return false;
}
LinePosition position;
LinePosition trackingLinePosition;
if (workspace.IsDocumentOpen(documentId) &&
(trackingLinePosition = GetTrackingLineColumn(document, index)) != LinePosition.Zero)
{
position = trackingLinePosition;
}
else
{
position = item.GetOriginalPosition();
}
return TryNavigateTo(workspace, documentId, position, previewTab, activate, cancellationToken);
}
// we don't use these
#pragma warning disable IDE0060 // Remove unused parameter - Implements interface method for sub-type
public object Identity(int index)
#pragma warning restore IDE0060 // Remove unused parameter
=> null;
public void StartCaching()
{
}
public void StopCaching()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Base implementation of ITableEntriesSnapshot
/// </summary>
internal abstract class AbstractTableEntriesSnapshot<TItem> : ITableEntriesSnapshot
where TItem : TableItem
{
// TODO : remove these once we move to new drop which contains API change from editor team
protected const string ProjectNames = StandardTableKeyNames.ProjectName + "s";
protected const string ProjectGuids = StandardTableKeyNames.ProjectGuid + "s";
private readonly int _version;
private readonly ImmutableArray<TItem> _items;
private ImmutableArray<ITrackingPoint> _trackingPoints;
protected AbstractTableEntriesSnapshot(int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints)
{
_version = version;
_items = items;
_trackingPoints = trackingPoints;
}
public abstract bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken);
public abstract bool TryGetValue(int index, string columnName, out object content);
public int VersionNumber
{
get
{
return _version;
}
}
public int Count
{
get
{
return _items.Length;
}
}
public int IndexOf(int index, ITableEntriesSnapshot newerSnapshot)
{
var item = GetItem(index);
if (item == null)
{
return -1;
}
if (!(newerSnapshot is AbstractTableEntriesSnapshot<TItem> ourSnapshot) || ourSnapshot.Count == 0)
{
// not ours, we don't know how to track index
return -1;
}
// quick path - this will deal with a case where we update data without any actual change
if (Count == ourSnapshot.Count)
{
var newItem = ourSnapshot.GetItem(index);
if (newItem != null && newItem.Equals(item))
{
return index;
}
}
// slow path.
for (var i = 0; i < ourSnapshot.Count; i++)
{
var newItem = ourSnapshot.GetItem(i);
if (item.EqualsIgnoringLocation(newItem))
{
return i;
}
}
// no similar item exist. table control itself will try to maintain selection
return -1;
}
public void StopTracking()
{
// remove tracking points
_trackingPoints = default;
}
public void Dispose()
=> StopTracking();
internal TItem GetItem(int index)
{
if (index < 0 || _items.Length <= index)
{
return null;
}
return _items[index];
}
protected LinePosition GetTrackingLineColumn(Document document, int index)
{
if (_trackingPoints.IsDefaultOrEmpty)
{
return LinePosition.Zero;
}
var trackingPoint = _trackingPoints[index];
if (!document.TryGetText(out var text))
{
return LinePosition.Zero;
}
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
return GetLinePosition(snapshot, trackingPoint);
}
var textBuffer = text.Container.TryGetTextBuffer();
if (textBuffer == null)
{
return LinePosition.Zero;
}
var currentSnapshot = textBuffer.CurrentSnapshot;
return GetLinePosition(currentSnapshot, trackingPoint);
}
private static LinePosition GetLinePosition(ITextSnapshot snapshot, ITrackingPoint trackingPoint)
{
var point = trackingPoint.GetPoint(snapshot);
var line = point.GetContainingLine();
return new LinePosition(line.LineNumber, point.Position - line.Start);
}
protected static bool TryNavigateTo(Workspace workspace, DocumentId documentId, LinePosition position, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
if (navigationService == null)
{
return false;
}
var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, previewTab)
.WithChangedOption(NavigationOptions.ActivateTab, activate);
return navigationService.TryNavigateToLineAndOffset(workspace, documentId, position.Line, position.Character, options, cancellationToken);
}
protected bool TryNavigateToItem(int index, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var item = GetItem(index);
var documentId = item?.DocumentId;
if (documentId == null)
{
return false;
}
var workspace = item.Workspace;
var solution = workspace.CurrentSolution;
var document = solution.GetDocument(documentId);
if (document == null)
{
return false;
}
LinePosition position;
LinePosition trackingLinePosition;
if (workspace.IsDocumentOpen(documentId) &&
(trackingLinePosition = GetTrackingLineColumn(document, index)) != LinePosition.Zero)
{
position = trackingLinePosition;
}
else
{
position = item.GetOriginalPosition();
}
return TryNavigateTo(workspace, documentId, position, previewTab, activate, cancellationToken);
}
// we don't use these
#pragma warning disable IDE0060 // Remove unused parameter - Implements interface method for sub-type
public object Identity(int index)
#pragma warning restore IDE0060 // Remove unused parameter
=> null;
public void StartCaching()
{
}
public void StopCaching()
{
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentBinder.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used for interiors of documentation comment
''' </summary>
Friend MustInherit Class DocumentationCommentBinder
Inherits Binder
Protected Sub New(containingBinder As Binder, commentedSymbol As Symbol)
MyBase.New(containingBinder)
CheckBinderSymbolRelationship(containingBinder, commentedSymbol)
Me.CommentedSymbol = commentedSymbol
End Sub
''' <summary>
''' Assuming there is one, the containing member of the binder is the commented symbol if and only if
''' the commented symbol is a non-delegate named type. (Otherwise, it is the containing type or namespace of the commented symbol.)
''' </summary>
''' <remarks>
''' Delegates don't have user-defined members, so it makes more sense to treat
''' them like methods.
''' </remarks>
<Conditional("DEBUG")>
Private Shared Sub CheckBinderSymbolRelationship(containingBinder As Binder, commentedSymbol As Symbol)
If commentedSymbol Is Nothing Then
Return
End If
Dim commentedNamedType = TryCast(commentedSymbol, NamedTypeSymbol)
Dim binderContainingMember As Symbol = containingBinder.ContainingMember
If commentedNamedType IsNot Nothing AndAlso commentedNamedType.TypeKind <> TypeKind.Delegate Then
Debug.Assert(binderContainingMember = commentedSymbol)
ElseIf commentedSymbol.ContainingType IsNot Nothing Then
Debug.Assert(TypeSymbol.Equals(DirectCast(binderContainingMember, TypeSymbol), commentedSymbol.ContainingType, TypeCompareKind.ConsiderEverything))
Else
' It's not worth writing a complicated check that handles merged namespaces.
Debug.Assert(binderContainingMember <> commentedSymbol)
Debug.Assert(binderContainingMember.Kind = SymbolKind.Namespace)
End If
End Sub
Friend Enum BinderType
None
Cref
NameInTypeParamRef
NameInTypeParam
NameInParamOrParamRef
End Enum
Public Shared Function IsIntrinsicTypeForDocumentationComment(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.ShortKeyword,
SyntaxKind.UShortKeyword,
SyntaxKind.IntegerKeyword,
SyntaxKind.UIntegerKeyword,
SyntaxKind.LongKeyword,
SyntaxKind.ULongKeyword,
SyntaxKind.DecimalKeyword,
SyntaxKind.SingleKeyword,
SyntaxKind.DoubleKeyword,
SyntaxKind.SByteKeyword,
SyntaxKind.ByteKeyword,
SyntaxKind.BooleanKeyword,
SyntaxKind.CharKeyword,
SyntaxKind.DateKeyword,
SyntaxKind.StringKeyword
Return True
Case Else
Return False
End Select
End Function
Friend Shared Function GetBinderTypeForNameAttribute(node As BaseXmlAttributeSyntax) As DocumentationCommentBinder.BinderType
Return GetBinderTypeForNameAttribute(GetParentXmlElementName(node))
End Function
Friend Shared Function GetBinderTypeForNameAttribute(parentNodeName As String) As DocumentationCommentBinder.BinderType
If parentNodeName IsNot Nothing Then
If DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterElementName, True) OrElse
DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterReferenceElementName, True) Then
Return DocumentationCommentBinder.BinderType.NameInParamOrParamRef
ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterElementName, True) Then
Return DocumentationCommentBinder.BinderType.NameInTypeParam
ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterReferenceElementName, True) Then
Return DocumentationCommentBinder.BinderType.NameInTypeParamRef
End If
End If
Return DocumentationCommentBinder.BinderType.None
End Function
Friend Shared Function GetParentXmlElementName(attr As BaseXmlAttributeSyntax) As String
Dim parent As VisualBasicSyntaxNode = attr.Parent
If parent Is Nothing Then
Return Nothing
End If
Select Case parent.Kind
Case SyntaxKind.XmlEmptyElement
Dim element = DirectCast(parent, XmlEmptyElementSyntax)
If element.Name.Kind <> SyntaxKind.XmlName Then
Return Nothing
End If
Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText
Case SyntaxKind.XmlElementStartTag
Dim element = DirectCast(parent, XmlElementStartTagSyntax)
If element.Name.Kind <> SyntaxKind.XmlName Then
Return Nothing
End If
Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText
End Select
Return Nothing
End Function
''' <summary>
''' Symbol commented with the documentation comment handled by this binder. In general,
''' all name lookup is being performed in context of this symbol's containing symbol.
''' We still need this symbol, though, to be able to find type parameters or parameters
''' referenced from 'param', 'paramref', 'typeparam' and 'typeparamref' tags.
''' </summary>
Protected ReadOnly CommentedSymbol As Symbol
Friend Overrides Function BindXmlNameAttributeValue(identifier As IdentifierNameSyntax, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides Function BindInsideCrefAttributeValue(name As TypeSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides Function BindInsideCrefAttributeValue(reference As CrefReferenceSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol)
Throw ExceptionUtilities.Unreachable
End Function
Protected Shared Function FindSymbolInSymbolArray(Of TSymbol As Symbol)(
name As String, symbols As ImmutableArray(Of TSymbol)) As ImmutableArray(Of Symbol)
If Not symbols.IsEmpty Then
For Each p In symbols
If IdentifierComparison.Equals(name, p.Name) Then
Return ImmutableArray.Create(Of Symbol)(p)
End If
Next
End If
Return ImmutableArray(Of Symbol).Empty
End Function
Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions
Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.UseBaseReferenceAccessibility
End Function
''' <summary>
''' Removes from symbol collection overridden methods or properties
''' </summary>
Protected Shared Sub RemoveOverriddenMethodsAndProperties(symbols As ArrayBuilder(Of Symbol))
If symbols Is Nothing OrElse symbols.Count < 2 Then
Return
End If
' Do we have any method or property?
Dim originalDef2Symbol As Dictionary(Of Symbol, Integer) = Nothing
For i = 0 To symbols.Count - 1
Dim sym As Symbol = symbols(i)
Select Case sym.Kind
Case SymbolKind.Method, SymbolKind.Property
If originalDef2Symbol Is Nothing Then
originalDef2Symbol = New Dictionary(Of Symbol, Integer)()
End If
originalDef2Symbol.Add(sym.OriginalDefinition, i)
End Select
Next
If originalDef2Symbol Is Nothing Then
Return
End If
' Do we need to remove any?
Dim indices2remove As ArrayBuilder(Of Integer) = Nothing
For i = 0 To symbols.Count - 1
Dim index As Integer = -1
Dim sym As Symbol = symbols(i)
Select Case sym.Kind
Case SymbolKind.Method
' Remove overridden methods
Dim method = DirectCast(sym.OriginalDefinition, MethodSymbol)
While True
method = method.OverriddenMethod
If method Is Nothing Then
Exit While
End If
If originalDef2Symbol.TryGetValue(method, index) Then
If indices2remove Is Nothing Then
indices2remove = ArrayBuilder(Of Integer).GetInstance
End If
indices2remove.Add(index)
End If
End While
Case SymbolKind.Property
' Remove overridden properties
Dim prop = DirectCast(sym.OriginalDefinition, PropertySymbol)
While True
prop = prop.OverriddenProperty
If prop Is Nothing Then
Exit While
End If
If originalDef2Symbol.TryGetValue(prop, index) Then
If indices2remove Is Nothing Then
indices2remove = ArrayBuilder(Of Integer).GetInstance
End If
indices2remove.Add(index)
End If
End While
End Select
Next
If indices2remove Is Nothing Then
Return
End If
' remove elements by indices from 'indices2remove'
For i = 0 To indices2remove.Count - 1
symbols(indices2remove(i)) = Nothing
Next
Dim target As Integer = 0
For source = 0 To symbols.Count - 1
Dim sym As Symbol = symbols(source)
If sym IsNot Nothing Then
symbols(target) = sym
target += 1
End If
Next
symbols.Clip(target)
indices2remove.Free()
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.Collections.Immutable
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used for interiors of documentation comment
''' </summary>
Friend MustInherit Class DocumentationCommentBinder
Inherits Binder
Protected Sub New(containingBinder As Binder, commentedSymbol As Symbol)
MyBase.New(containingBinder)
CheckBinderSymbolRelationship(containingBinder, commentedSymbol)
Me.CommentedSymbol = commentedSymbol
End Sub
''' <summary>
''' Assuming there is one, the containing member of the binder is the commented symbol if and only if
''' the commented symbol is a non-delegate named type. (Otherwise, it is the containing type or namespace of the commented symbol.)
''' </summary>
''' <remarks>
''' Delegates don't have user-defined members, so it makes more sense to treat
''' them like methods.
''' </remarks>
<Conditional("DEBUG")>
Private Shared Sub CheckBinderSymbolRelationship(containingBinder As Binder, commentedSymbol As Symbol)
If commentedSymbol Is Nothing Then
Return
End If
Dim commentedNamedType = TryCast(commentedSymbol, NamedTypeSymbol)
Dim binderContainingMember As Symbol = containingBinder.ContainingMember
If commentedNamedType IsNot Nothing AndAlso commentedNamedType.TypeKind <> TypeKind.Delegate Then
Debug.Assert(binderContainingMember = commentedSymbol)
ElseIf commentedSymbol.ContainingType IsNot Nothing Then
Debug.Assert(TypeSymbol.Equals(DirectCast(binderContainingMember, TypeSymbol), commentedSymbol.ContainingType, TypeCompareKind.ConsiderEverything))
Else
' It's not worth writing a complicated check that handles merged namespaces.
Debug.Assert(binderContainingMember <> commentedSymbol)
Debug.Assert(binderContainingMember.Kind = SymbolKind.Namespace)
End If
End Sub
Friend Enum BinderType
None
Cref
NameInTypeParamRef
NameInTypeParam
NameInParamOrParamRef
End Enum
Public Shared Function IsIntrinsicTypeForDocumentationComment(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.ShortKeyword,
SyntaxKind.UShortKeyword,
SyntaxKind.IntegerKeyword,
SyntaxKind.UIntegerKeyword,
SyntaxKind.LongKeyword,
SyntaxKind.ULongKeyword,
SyntaxKind.DecimalKeyword,
SyntaxKind.SingleKeyword,
SyntaxKind.DoubleKeyword,
SyntaxKind.SByteKeyword,
SyntaxKind.ByteKeyword,
SyntaxKind.BooleanKeyword,
SyntaxKind.CharKeyword,
SyntaxKind.DateKeyword,
SyntaxKind.StringKeyword
Return True
Case Else
Return False
End Select
End Function
Friend Shared Function GetBinderTypeForNameAttribute(node As BaseXmlAttributeSyntax) As DocumentationCommentBinder.BinderType
Return GetBinderTypeForNameAttribute(GetParentXmlElementName(node))
End Function
Friend Shared Function GetBinderTypeForNameAttribute(parentNodeName As String) As DocumentationCommentBinder.BinderType
If parentNodeName IsNot Nothing Then
If DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterElementName, True) OrElse
DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterReferenceElementName, True) Then
Return DocumentationCommentBinder.BinderType.NameInParamOrParamRef
ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterElementName, True) Then
Return DocumentationCommentBinder.BinderType.NameInTypeParam
ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterReferenceElementName, True) Then
Return DocumentationCommentBinder.BinderType.NameInTypeParamRef
End If
End If
Return DocumentationCommentBinder.BinderType.None
End Function
Friend Shared Function GetParentXmlElementName(attr As BaseXmlAttributeSyntax) As String
Dim parent As VisualBasicSyntaxNode = attr.Parent
If parent Is Nothing Then
Return Nothing
End If
Select Case parent.Kind
Case SyntaxKind.XmlEmptyElement
Dim element = DirectCast(parent, XmlEmptyElementSyntax)
If element.Name.Kind <> SyntaxKind.XmlName Then
Return Nothing
End If
Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText
Case SyntaxKind.XmlElementStartTag
Dim element = DirectCast(parent, XmlElementStartTagSyntax)
If element.Name.Kind <> SyntaxKind.XmlName Then
Return Nothing
End If
Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText
End Select
Return Nothing
End Function
''' <summary>
''' Symbol commented with the documentation comment handled by this binder. In general,
''' all name lookup is being performed in context of this symbol's containing symbol.
''' We still need this symbol, though, to be able to find type parameters or parameters
''' referenced from 'param', 'paramref', 'typeparam' and 'typeparamref' tags.
''' </summary>
Protected ReadOnly CommentedSymbol As Symbol
Friend Overrides Function BindXmlNameAttributeValue(identifier As IdentifierNameSyntax, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides Function BindInsideCrefAttributeValue(name As TypeSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides Function BindInsideCrefAttributeValue(reference As CrefReferenceSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol)
Throw ExceptionUtilities.Unreachable
End Function
Protected Shared Function FindSymbolInSymbolArray(Of TSymbol As Symbol)(
name As String, symbols As ImmutableArray(Of TSymbol)) As ImmutableArray(Of Symbol)
If Not symbols.IsEmpty Then
For Each p In symbols
If IdentifierComparison.Equals(name, p.Name) Then
Return ImmutableArray.Create(Of Symbol)(p)
End If
Next
End If
Return ImmutableArray(Of Symbol).Empty
End Function
Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions
Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.UseBaseReferenceAccessibility
End Function
''' <summary>
''' Removes from symbol collection overridden methods or properties
''' </summary>
Protected Shared Sub RemoveOverriddenMethodsAndProperties(symbols As ArrayBuilder(Of Symbol))
If symbols Is Nothing OrElse symbols.Count < 2 Then
Return
End If
' Do we have any method or property?
Dim originalDef2Symbol As Dictionary(Of Symbol, Integer) = Nothing
For i = 0 To symbols.Count - 1
Dim sym As Symbol = symbols(i)
Select Case sym.Kind
Case SymbolKind.Method, SymbolKind.Property
If originalDef2Symbol Is Nothing Then
originalDef2Symbol = New Dictionary(Of Symbol, Integer)()
End If
originalDef2Symbol.Add(sym.OriginalDefinition, i)
End Select
Next
If originalDef2Symbol Is Nothing Then
Return
End If
' Do we need to remove any?
Dim indices2remove As ArrayBuilder(Of Integer) = Nothing
For i = 0 To symbols.Count - 1
Dim index As Integer = -1
Dim sym As Symbol = symbols(i)
Select Case sym.Kind
Case SymbolKind.Method
' Remove overridden methods
Dim method = DirectCast(sym.OriginalDefinition, MethodSymbol)
While True
method = method.OverriddenMethod
If method Is Nothing Then
Exit While
End If
If originalDef2Symbol.TryGetValue(method, index) Then
If indices2remove Is Nothing Then
indices2remove = ArrayBuilder(Of Integer).GetInstance
End If
indices2remove.Add(index)
End If
End While
Case SymbolKind.Property
' Remove overridden properties
Dim prop = DirectCast(sym.OriginalDefinition, PropertySymbol)
While True
prop = prop.OverriddenProperty
If prop Is Nothing Then
Exit While
End If
If originalDef2Symbol.TryGetValue(prop, index) Then
If indices2remove Is Nothing Then
indices2remove = ArrayBuilder(Of Integer).GetInstance
End If
indices2remove.Add(index)
End If
End While
End Select
Next
If indices2remove Is Nothing Then
Return
End If
' remove elements by indices from 'indices2remove'
For i = 0 To indices2remove.Count - 1
symbols(indices2remove(i)) = Nothing
Next
Dim target As Integer = 0
For source = 0 To symbols.Count - 1
Dim sym As Symbol = symbols(source)
If sym IsNot Nothing Then
symbols(target) = sym
target += 1
End If
Next
symbols.Clip(target)
indices2remove.Free()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/JoinKeywordRecommender.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 "Join" keyword.
''' </summary>
Friend Class JoinKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Join", VBFeaturesResources.Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
' First there is the normal and boring "Join"
If context.IsQueryOperatorContext OrElse context.IsAdditionalJoinOperatorContext(cancellationToken) Then
Return s_keywords
End If
' Now this might be Group Join...
Dim targetToken = context.TargetToken
' If it's just "Group" it may have parsed as a Group By
Return If(targetToken.IsChildToken(Of GroupByClauseSyntax)(Function(groupBy) groupBy.GroupKeyword) OrElse targetToken.IsChildToken(Of GroupJoinClauseSyntax)(Function(groupBy) groupBy.GroupKeyword),
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 "Join" keyword.
''' </summary>
Friend Class JoinKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Join", VBFeaturesResources.Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
' First there is the normal and boring "Join"
If context.IsQueryOperatorContext OrElse context.IsAdditionalJoinOperatorContext(cancellationToken) Then
Return s_keywords
End If
' Now this might be Group Join...
Dim targetToken = context.TargetToken
' If it's just "Group" it may have parsed as a Group By
Return If(targetToken.IsChildToken(Of GroupByClauseSyntax)(Function(groupBy) groupBy.GroupKeyword) OrElse targetToken.IsChildToken(Of GroupJoinClauseSyntax)(Function(groupBy) groupBy.GroupKeyword),
s_keywords,
ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/EditorFeatures/VisualBasicTest/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.AddConstructorParametersFromMembers
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddConstructorParametersFromMembers
Public Class AddConstructorParametersFromMembersTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New AddConstructorParametersFromMembersCodeRefactoringProvider()
End Function
Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return FlattenActions(actions)
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAdd1() As Task
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String|]
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Public Sub New(i As Integer, s As String)
Me.i = i
Me.s = s
End Sub
End Class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddOptional1() As Task
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String|]
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Public Sub New(i As Integer, Optional s As String = Nothing)
Me.i = i
Me.s = s
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_optional_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddToConstructorWithMostMatchingParameters1() As Task
' behavior change with 33603, now all constructors offered
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String
Private b As Boolean|]
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String)
Me.New(i)
Me.s = s
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private b As Boolean
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String, b As Boolean)
Me.New(i)
Me.s = s
Me.b = b
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, String)"))
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddOptionalToConstructorWithMostMatchingParameters1() As Task
' behavior change with 33603, now all constructors offered
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String
Private b As Boolean|]
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String)
Me.New(i)
Me.s = s
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private b As Boolean
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String, Optional b As Boolean = Nothing)
Me.New(i)
Me.s = s
Me.b = b
End Sub
End Class", index:=3, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, String)"))
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddParamtersToConstructorBySelectOneMember() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
[|Private k As Integer|]
Private j As Integer
Public Sub New(i As Integer, j As Integer)
Me.i = i
Me.j = j
End Sub
End Class",
"Class Program
Private i As Integer
Private k As Integer
Private j As Integer
Public Sub New(i As Integer, j As Integer, k As Integer)
Me.i = i
Me.j = j
Me.k = k
End Sub
End Class")
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestParametersAreStillRightIfMembersAreOutOfOrder() As Task
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private k As Integer
Private j As Integer|]
Public Sub New(i As Integer, j As Integer)
Me.i = i
Me.j = j
End Sub
End Class",
"Class Program
[|Private i As Integer
Private k As Integer
Private j As Integer|]
Public Sub New(i As Integer, j As Integer, k As Integer)
Me.i = i
Me.j = j
Me.k = k
End Sub
End Class")
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNormalProperty() As Task
Await TestInRegularAndScriptAsync(
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New(i As Integer)
End Sub
End Class",
"
Class Program
Private i As Integer
Property Hello As Integer = 1
Public Sub New(i As Integer, hello As Integer)
Me.Hello = hello
End Sub
End Class"
)
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMissingIfFieldsAndPropertyAlreadyExists() As Task
Await TestMissingAsync(
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New(i As Integer, hello As Integer)
End Sub
End Class")
End Function
<WorkItem(33602, "https://github.com/dotnet/roslyn/issues/33602")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestConstructorWithNoParameters() As Task
Await TestInRegularAndScriptAsync(
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New()
End Sub
End Class",
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New(i As Integer, hello As Integer)
Me.i = i
Me.Hello = hello
End Sub
End Class"
)
End Function
<WorkItem(33602, "https://github.com/dotnet/roslyn/issues/33602")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestDefaultConstructor() As Task
Await TestMissingAsync(
"
Class Program
[|Private i As Integer|]
End Class"
)
End Function
<WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestPartialSelection() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
Private [|s|] As String
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Public Sub New(i As Integer, s As String)
Me.i = i
Me.s = s
End Sub
End Class")
End Function
<WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultiplePartialSelection() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
Private [|s As String
Private j|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private j As Integer
Public Sub New(i As Integer, s As String, j As Integer)
Me.i = i
Me.s = s
Me.j = j
End Sub
End Class")
End Function
<WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultiplePartialSelection2() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
Private [|s As String
Private |]j As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private j As Integer
Public Sub New(i As Integer, s As String)
Me.i = i
Me.s = s
End Sub
End Class")
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_FirstOfThree() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer, l As Integer)
Me.i = i
Me.l = l
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class", index:=0, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_SecondOfThree() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer, l As Integer)
Me.l = l
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_ThirdOfThree() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer, l As Integer)
Me.l = l
End Sub
End Class", index:=2, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Integer, Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_OneMustBeOptional() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
' index 0 as required
' index 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing)
End Sub
' index 1 as required
' index 4 as optional
Public Sub New(i As Integer, j As Double)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
' index 0 as required
' index 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing)
End Sub
' index 1 as required
' index 4 as optional
Public Sub New(i As Integer, j As Double, l As Integer)
Me.l = l
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Double)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_OneMustBeOptional2() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
' index 0, and 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing)
End Sub
' index 1, and 4 as optional
Public Sub New(i As Integer, j As Double)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
' index 0, and 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing, Optional l As Integer = Nothing)
Me.l = l
End Sub
' index 1, and 4 as optional
Public Sub New(i As Integer, j As Double)
End Sub
End Class", index:=3, title:=String.Format(FeaturesResources.Add_to_0, "Program(Double)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_AllMustBeOptional1() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|p|] As Integer
Public Sub New(Optional i As Integer = Nothing)
Me.i = i
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing)
End Sub
End Class",
"Class Program
Private p As Integer
Public Sub New(Optional i As Integer = Nothing, Optional p As Integer = Nothing)
Me.i = i
Me.p = p
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing)
End Sub
End Class", index:=0, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_AllMustBeOptional2() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|p|] As Integer
Public Sub New(Optional i As Integer = Nothing)
Me.i = i
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing)
End Sub
End Class",
"Class Program
Private p As Integer
Public Sub New(Optional i As Integer = Nothing)
Me.i = i
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing, Optional p As Integer = Nothing)
Me.p = p
End Sub
End Class", index:=2, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Integer, Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
public async function TestNonSelection1() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
[||] dim s As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection2() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
[||]dim s As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection3() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
dim [||]s As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection4() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
dim s[||] As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection5() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String [||]
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar1() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
[||]dim s, t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String, t As String)
Me.i = i
Me.s = s
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar2() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String[||]
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String, t As String)
Me.i = i
Me.s = s
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar3() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim [||]s, t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar4() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s[||], t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar5() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, [||]t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, t As String)
Me.i = i
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar6() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t[||] As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, t As String)
Me.i = i
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing1() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
[||]
dim s, t As String
public sub new(i As Integer)
Me.i = i
end sub
}")
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing2() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
{
dim i As Integer
d[||]im s, t As String
public sub new(i As Integer)
Me.i = i
end sub
}")
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing3() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim[||] s, t As String
public sub new(i As Integer)
{
Me.i = i
end sub
}")
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing4() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s,[||] t As String
public sub new(i As Integer)
Me.i = i
end sub
}")
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 Microsoft.CodeAnalysis.AddConstructorParametersFromMembers
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddConstructorParametersFromMembers
Public Class AddConstructorParametersFromMembersTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New AddConstructorParametersFromMembersCodeRefactoringProvider()
End Function
Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return FlattenActions(actions)
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAdd1() As Task
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String|]
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Public Sub New(i As Integer, s As String)
Me.i = i
Me.s = s
End Sub
End Class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddOptional1() As Task
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String|]
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Public Sub New(i As Integer, Optional s As String = Nothing)
Me.i = i
Me.s = s
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_optional_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddToConstructorWithMostMatchingParameters1() As Task
' behavior change with 33603, now all constructors offered
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String
Private b As Boolean|]
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String)
Me.New(i)
Me.s = s
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private b As Boolean
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String, b As Boolean)
Me.New(i)
Me.s = s
Me.b = b
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, String)"))
End Function
<WorkItem(530592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530592")>
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddOptionalToConstructorWithMostMatchingParameters1() As Task
' behavior change with 33603, now all constructors offered
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private s As String
Private b As Boolean|]
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String)
Me.New(i)
Me.s = s
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private b As Boolean
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, s As String, Optional b As Boolean = Nothing)
Me.New(i)
Me.s = s
Me.b = b
End Sub
End Class", index:=3, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, String)"))
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestAddParamtersToConstructorBySelectOneMember() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
[|Private k As Integer|]
Private j As Integer
Public Sub New(i As Integer, j As Integer)
Me.i = i
Me.j = j
End Sub
End Class",
"Class Program
Private i As Integer
Private k As Integer
Private j As Integer
Public Sub New(i As Integer, j As Integer, k As Integer)
Me.i = i
Me.j = j
Me.k = k
End Sub
End Class")
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestParametersAreStillRightIfMembersAreOutOfOrder() As Task
Await TestInRegularAndScriptAsync(
"Class Program
[|Private i As Integer
Private k As Integer
Private j As Integer|]
Public Sub New(i As Integer, j As Integer)
Me.i = i
Me.j = j
End Sub
End Class",
"Class Program
[|Private i As Integer
Private k As Integer
Private j As Integer|]
Public Sub New(i As Integer, j As Integer, k As Integer)
Me.i = i
Me.j = j
Me.k = k
End Sub
End Class")
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNormalProperty() As Task
Await TestInRegularAndScriptAsync(
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New(i As Integer)
End Sub
End Class",
"
Class Program
Private i As Integer
Property Hello As Integer = 1
Public Sub New(i As Integer, hello As Integer)
Me.Hello = hello
End Sub
End Class"
)
End Function
<WorkItem(28775, "https://github.com/dotnet/roslyn/issues/28775")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMissingIfFieldsAndPropertyAlreadyExists() As Task
Await TestMissingAsync(
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New(i As Integer, hello As Integer)
End Sub
End Class")
End Function
<WorkItem(33602, "https://github.com/dotnet/roslyn/issues/33602")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestConstructorWithNoParameters() As Task
Await TestInRegularAndScriptAsync(
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New()
End Sub
End Class",
"
Class Program
[|Private i As Integer
Property Hello As Integer = 1|]
Public Sub New(i As Integer, hello As Integer)
Me.i = i
Me.Hello = hello
End Sub
End Class"
)
End Function
<WorkItem(33602, "https://github.com/dotnet/roslyn/issues/33602")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestDefaultConstructor() As Task
Await TestMissingAsync(
"
Class Program
[|Private i As Integer|]
End Class"
)
End Function
<WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestPartialSelection() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
Private [|s|] As String
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Public Sub New(i As Integer, s As String)
Me.i = i
Me.s = s
End Sub
End Class")
End Function
<WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultiplePartialSelection() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
Private [|s As String
Private j|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private j As Integer
Public Sub New(i As Integer, s As String, j As Integer)
Me.i = i
Me.s = s
Me.j = j
End Sub
End Class")
End Function
<WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultiplePartialSelection2() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private i As Integer
Private [|s As String
Private |]j As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
End Class",
"Class Program
Private i As Integer
Private s As String
Private j As Integer
Public Sub New(i As Integer, s As String)
Me.i = i
Me.s = s
End Sub
End Class")
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_FirstOfThree() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer, l As Integer)
Me.i = i
Me.l = l
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class", index:=0, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_SecondOfThree() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer, l As Integer)
Me.l = l
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_ThirdOfThree() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
Public Sub New(i As Integer)
Me.i = i
End Sub
Public Sub New(i As Integer, j As Integer)
End Sub
Public Sub New(i As Integer, j As Integer, k As Integer, l As Integer)
Me.l = l
End Sub
End Class", index:=2, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Integer, Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_OneMustBeOptional() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
' index 0 as required
' index 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing)
End Sub
' index 1 as required
' index 4 as optional
Public Sub New(i As Integer, j As Double)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
' index 0 as required
' index 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing)
End Sub
' index 1 as required
' index 4 as optional
Public Sub New(i As Integer, j As Double, l As Integer)
Me.l = l
End Sub
End Class", index:=1, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Double)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_OneMustBeOptional2() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|l|] As Integer
' index 0, and 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing)
End Sub
' index 1, and 4 as optional
Public Sub New(i As Integer, j As Double)
End Sub
End Class",
"Class Program
Private [|l|] As Integer
' index 0, and 2 as optional
Public Sub New(i As Integer)
Me.i = i
End Sub
' index 3 as optional
Public Sub New(Optional j As Double = Nothing, Optional l As Integer = Nothing)
Me.l = l
End Sub
' index 1, and 4 as optional
Public Sub New(i As Integer, j As Double)
End Sub
End Class", index:=3, title:=String.Format(FeaturesResources.Add_to_0, "Program(Double)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_AllMustBeOptional1() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|p|] As Integer
Public Sub New(Optional i As Integer = Nothing)
Me.i = i
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing)
End Sub
End Class",
"Class Program
Private p As Integer
Public Sub New(Optional i As Integer = Nothing, Optional p As Integer = Nothing)
Me.i = i
Me.p = p
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing)
End Sub
End Class", index:=0, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer)"))
End Function
<WorkItem(33603, "https://github.com/dotnet/roslyn/issues/33603")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestMultipleConstructors_AllMustBeOptional2() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private [|p|] As Integer
Public Sub New(Optional i As Integer = Nothing)
Me.i = i
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing)
End Sub
End Class",
"Class Program
Private p As Integer
Public Sub New(Optional i As Integer = Nothing)
Me.i = i
End Sub
Public Sub New(j As Double, Optional k As Double = Nothing)
End Sub
Public Sub New(l As Integer, m As Integer, Optional n As Integer = Nothing, Optional p As Integer = Nothing)
Me.p = p
End Sub
End Class", index:=2, title:=String.Format(FeaturesResources.Add_to_0, "Program(Integer, Integer, Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
public async function TestNonSelection1() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
[||] dim s As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection2() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
[||]dim s As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection3() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
dim [||]s As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection4() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
dim s[||] As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelection5() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String [||]
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collections.Generic
class Program
dim i As Integer
dim s As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar1() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
[||]dim s, t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String, t As String)
Me.i = i
Me.s = s
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar2() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String[||]
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String, t As String)
Me.i = i
Me.s = s
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar3() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim [||]s, t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar4() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s[||], t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, s As String)
Me.i = i
Me.s = s
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar5() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, [||]t As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, t As String)
Me.i = i
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMultiVar6() As Task
Await TestInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t[||] As String
public sub new(i As Integer)
Me.i = i
end sub
end class",
"imports System.Collection.Generic
class Program
dim i As Integer
dim s, t As String
public sub new(i As Integer, t As String)
Me.i = i
Me.t = t
end sub
end class", title:=String.Format(FeaturesResources.Add_parameters_to_0, "Program(Integer)"))
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing1() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
[||]
dim s, t As String
public sub new(i As Integer)
Me.i = i
end sub
}")
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing2() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
{
dim i As Integer
d[||]im s, t As String
public sub new(i As Integer)
Me.i = i
end sub
}")
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing3() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim[||] s, t As String
public sub new(i As Integer)
{
Me.i = i
end sub
}")
End Function
<WorkItem(23271, "https://github.com/dotnet/roslyn/issues/23271")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddConstructorParametersFromMembers)>
Public Async Function TestNonSelectionMissing4() As Task
Await TestMissingInRegularAndScriptAsync(
"imports System.Collection.Generic
class Program
dim i As Integer
dim s,[||] t As String
public sub new(i As Integer)
Me.i = i
end sub
}")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ReadOnlyKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ReadOnlyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.StaticKeyword,
};
public ReadOnlyKeywordRecommender()
: base(SyntaxKind.ReadOnlyKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsGlobalStatementContext ||
IsRefReadOnlyContext(context) ||
IsValidContextForType(context, cancellationToken) ||
context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: s_validMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken) ||
IsStructAccessorContext(context);
}
private static bool IsRefReadOnlyContext(CSharpSyntaxContext context)
=> context.TargetToken.IsKind(SyntaxKind.RefKeyword) &&
(context.TargetToken.Parent.IsKind(SyntaxKind.RefType) || context.IsFunctionPointerTypeArgumentContext);
private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: true, cancellationToken);
}
private static bool IsStructAccessorContext(CSharpSyntaxContext context)
{
var type = context.ContainingTypeDeclaration;
return type is not null &&
type.Kind() is SyntaxKind.StructDeclaration or SyntaxKind.RecordStructDeclaration &&
context.TargetToken.IsAnyAccessorDeclarationContext(context.Position, SyntaxKind.ReadOnlyKeyword);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ReadOnlyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.StaticKeyword,
};
public ReadOnlyKeywordRecommender()
: base(SyntaxKind.ReadOnlyKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsGlobalStatementContext ||
IsRefReadOnlyContext(context) ||
IsValidContextForType(context, cancellationToken) ||
context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: s_validMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken) ||
IsStructAccessorContext(context);
}
private static bool IsRefReadOnlyContext(CSharpSyntaxContext context)
=> context.TargetToken.IsKind(SyntaxKind.RefKeyword) &&
(context.TargetToken.Parent.IsKind(SyntaxKind.RefType) || context.IsFunctionPointerTypeArgumentContext);
private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: true, cancellationToken);
}
private static bool IsStructAccessorContext(CSharpSyntaxContext context)
{
var type = context.ContainingTypeDeclaration;
return type is not null &&
type.Kind() is SyntaxKind.StructDeclaration or SyntaxKind.RecordStructDeclaration &&
context.TargetToken.IsAnyAccessorDeclarationContext(context.Position, SyntaxKind.ReadOnlyKeyword);
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzersCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.ComponentModel.Composition;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.CodeAnalysis;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSLangProj140;
using Workspace = Microsoft.CodeAnalysis.Workspace;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
[Export]
internal class AnalyzersCommandHandler : IAnalyzersCommandHandler, IVsUpdateSolutionEvents
{
private readonly AnalyzerItemsTracker _tracker;
private readonly AnalyzerReferenceManager _analyzerReferenceManager;
private readonly IServiceProvider _serviceProvider;
private ContextMenuController _analyzerFolderContextMenuController;
private ContextMenuController _analyzerContextMenuController;
private ContextMenuController _diagnosticContextMenuController;
// Analyzers folder context menu items
private MenuCommand _addMenuItem;
// Analyzer context menu items
private MenuCommand _removeMenuItem;
// Diagnostic context menu items
private MenuCommand _setSeverityDefaultMenuItem;
private MenuCommand _setSeverityErrorMenuItem;
private MenuCommand _setSeverityWarningMenuItem;
private MenuCommand _setSeverityInfoMenuItem;
private MenuCommand _setSeverityHiddenMenuItem;
private MenuCommand _setSeverityNoneMenuItem;
private MenuCommand _openHelpLinkMenuItem;
// Other menu items
private MenuCommand _projectAddMenuItem;
private MenuCommand _projectContextAddMenuItem;
private MenuCommand _referencesContextAddMenuItem;
private MenuCommand _setActiveRuleSetMenuItem;
private Workspace _workspace;
private bool _allowProjectSystemOperations = true;
private bool _initialized;
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public AnalyzersCommandHandler(
AnalyzerItemsTracker tracker,
AnalyzerReferenceManager analyzerReferenceManager,
[Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
{
_tracker = tracker;
_analyzerReferenceManager = analyzerReferenceManager;
_serviceProvider = serviceProvider;
}
/// <summary>
/// Hook up the context menu handlers.
/// </summary>
public void Initialize(IMenuCommandService menuCommandService)
{
if (menuCommandService != null)
{
// Analyzers folder context menu items
_addMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.AddAnalyzer, AddAnalyzerHandler);
_ = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenRuleSet, OpenRuleSetHandler);
// Analyzer context menu items
_removeMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.RemoveAnalyzer, RemoveAnalyzerHandler);
// Diagnostic context menu items
_setSeverityDefaultMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityDefault, SetSeverityHandler);
_setSeverityErrorMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityError, SetSeverityHandler);
_setSeverityWarningMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityWarning, SetSeverityHandler);
_setSeverityInfoMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityInfo, SetSeverityHandler);
_setSeverityHiddenMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityHidden, SetSeverityHandler);
_setSeverityNoneMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityNone, SetSeverityHandler);
_openHelpLinkMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenDiagnosticHelpLink, OpenDiagnosticHelpLinkHandler);
// Other menu items
_projectAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectAddAnalyzer, AddAnalyzerHandler);
_projectContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectContextAddAnalyzer, AddAnalyzerHandler);
_referencesContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ReferencesContextAddAnalyzer, AddAnalyzerHandler);
_setActiveRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetActiveRuleSet, SetActiveRuleSetHandler);
UpdateOtherMenuItemsVisibility();
if (_tracker != null)
{
_tracker.SelectedHierarchyItemChanged += SelectedHierarchyItemChangedHandler;
}
var buildManager = (IVsSolutionBuildManager)_serviceProvider.GetService(typeof(SVsSolutionBuildManager));
buildManager.AdviseUpdateSolutionEvents(this, out var cookie);
_initialized = true;
}
}
public IContextMenuController AnalyzerFolderContextMenuController
{
get
{
if (_analyzerFolderContextMenuController == null)
{
_analyzerFolderContextMenuController = new ContextMenuController(
ID.RoslynCommands.AnalyzerFolderContextMenu,
ShouldShowAnalyzerFolderContextMenu,
UpdateAnalyzerFolderContextMenu);
}
return _analyzerFolderContextMenuController;
}
}
private bool ShouldShowAnalyzerFolderContextMenu(IEnumerable<object> items)
{
return items.Count() == 1;
}
private void UpdateAnalyzerFolderContextMenu()
{
if (_addMenuItem != null)
{
_addMenuItem.Visible = SelectedProjectSupportsAnalyzers();
_addMenuItem.Enabled = _allowProjectSystemOperations;
}
}
public IContextMenuController AnalyzerContextMenuController
{
get
{
if (_analyzerContextMenuController == null)
{
_analyzerContextMenuController = new ContextMenuController(
ID.RoslynCommands.AnalyzerContextMenu,
ShouldShowAnalyzerContextMenu,
UpdateAnalyzerContextMenu);
}
return _analyzerContextMenuController;
}
}
private bool ShouldShowAnalyzerContextMenu(IEnumerable<object> items)
{
return items.All(item => item is AnalyzerItem);
}
private void UpdateAnalyzerContextMenu()
{
if (_removeMenuItem != null)
{
_removeMenuItem.Enabled = _allowProjectSystemOperations;
}
}
public IContextMenuController DiagnosticContextMenuController
{
get
{
if (_diagnosticContextMenuController == null)
{
_diagnosticContextMenuController = new ContextMenuController(
ID.RoslynCommands.DiagnosticContextMenu,
ShouldShowDiagnosticContextMenu,
UpdateDiagnosticContextMenu);
}
return _diagnosticContextMenuController;
}
}
private bool ShouldShowDiagnosticContextMenu(IEnumerable<object> items)
{
return _initialized && items.All(item => item is DiagnosticItem);
}
private void UpdateDiagnosticContextMenu()
{
Debug.Assert(_initialized);
UpdateSeverityMenuItemsChecked();
UpdateSeverityMenuItemsEnabled();
UpdateOpenHelpLinkMenuItemVisibility();
}
private MenuCommand AddCommandHandler(IMenuCommandService menuCommandService, int roslynCommand, EventHandler handler)
{
var commandID = new CommandID(Guids.RoslynGroupId, roslynCommand);
var menuCommand = new MenuCommand(handler, commandID);
menuCommandService.AddCommand(menuCommand);
return menuCommand;
}
private void SelectedHierarchyItemChangedHandler(object sender, EventArgs e)
{
UpdateOtherMenuItemsVisibility();
}
private void UpdateOtherMenuItemsVisibility()
{
var selectedProjectSupportsAnalyzers = SelectedProjectSupportsAnalyzers();
_projectAddMenuItem.Visible = selectedProjectSupportsAnalyzers;
_projectContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedItemId == VSConstants.VSITEMID_ROOT;
_referencesContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers;
_setActiveRuleSetMenuItem.Visible = selectedProjectSupportsAnalyzers &&
_tracker.SelectedHierarchy.TryGetItemName(_tracker.SelectedItemId, out var itemName) &&
Path.GetExtension(itemName).Equals(".ruleset", StringComparison.OrdinalIgnoreCase);
}
private void UpdateOtherMenuItemsEnabled()
{
_projectAddMenuItem.Enabled = _allowProjectSystemOperations;
_projectContextAddMenuItem.Enabled = _allowProjectSystemOperations;
_referencesContextAddMenuItem.Enabled = _allowProjectSystemOperations;
_removeMenuItem.Enabled = _allowProjectSystemOperations;
}
private void UpdateOpenHelpLinkMenuItemVisibility()
{
_openHelpLinkMenuItem.Visible = _tracker.SelectedDiagnosticItems.Length == 1 &&
_tracker.SelectedDiagnosticItems[0].GetHelpLink() != null;
}
private void UpdateSeverityMenuItemsChecked()
{
_setSeverityDefaultMenuItem.Checked = false;
_setSeverityErrorMenuItem.Checked = false;
_setSeverityWarningMenuItem.Checked = false;
_setSeverityInfoMenuItem.Checked = false;
_setSeverityHiddenMenuItem.Checked = false;
_setSeverityNoneMenuItem.Checked = false;
var workspace = TryGetWorkspace() as VisualStudioWorkspace;
if (workspace == null)
{
return;
}
var selectedItemSeverities = new HashSet<ReportDiagnostic>();
var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.ProjectId);
foreach (var group in groups)
{
var project = workspace.CurrentSolution.GetProject(group.Key);
if (project == null)
{
continue;
}
var analyzerConfigOptions = project.GetAnalyzerConfigOptions();
foreach (var diagnosticItem in group)
{
var severity = diagnosticItem.Descriptor.GetEffectiveSeverity(project.CompilationOptions, analyzerConfigOptions);
selectedItemSeverities.Add(severity);
}
}
if (selectedItemSeverities.Count != 1)
{
return;
}
switch (selectedItemSeverities.Single())
{
case ReportDiagnostic.Default:
_setSeverityDefaultMenuItem.Checked = true;
break;
case ReportDiagnostic.Error:
_setSeverityErrorMenuItem.Checked = true;
break;
case ReportDiagnostic.Warn:
_setSeverityWarningMenuItem.Checked = true;
break;
case ReportDiagnostic.Info:
_setSeverityInfoMenuItem.Checked = true;
break;
case ReportDiagnostic.Hidden:
_setSeverityHiddenMenuItem.Checked = true;
break;
case ReportDiagnostic.Suppress:
_setSeverityNoneMenuItem.Checked = true;
break;
default:
break;
}
}
private void UpdateSeverityMenuItemsEnabled()
{
var configurable = !_tracker.SelectedDiagnosticItems.Any(item => item.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.NotConfigurable));
_setSeverityDefaultMenuItem.Enabled = configurable;
_setSeverityErrorMenuItem.Enabled = configurable;
_setSeverityWarningMenuItem.Enabled = configurable;
_setSeverityInfoMenuItem.Enabled = configurable;
_setSeverityHiddenMenuItem.Enabled = configurable;
_setSeverityNoneMenuItem.Enabled = configurable;
}
private bool SelectedProjectSupportsAnalyzers()
{
return _tracker != null &&
_tracker.SelectedHierarchy != null &&
_tracker.SelectedHierarchy.TryGetProject(out var project) &&
project.Object is VSProject3;
}
/// <summary>
/// Handler for "Add Analyzer..." context menu on Analyzers folder node.
/// </summary>
internal void AddAnalyzerHandler(object sender, EventArgs args)
{
if (_analyzerReferenceManager != null)
{
_analyzerReferenceManager.ShowDialog();
}
}
/// <summary>
/// Handler for "Remove" context menu on individual Analyzer items.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
internal void RemoveAnalyzerHandler(object sender, EventArgs args)
{
foreach (var item in _tracker.SelectedAnalyzerItems)
{
item.Remove();
}
}
internal void OpenRuleSetHandler(object sender, EventArgs args)
{
if (_tracker.SelectedFolder != null &&
_serviceProvider != null)
{
var workspace = _tracker.SelectedFolder.Workspace as VisualStudioWorkspace;
var projectId = _tracker.SelectedFolder.ProjectId;
if (workspace != null)
{
var ruleSetFile = workspace.TryGetRuleSetPathForProject(projectId);
if (ruleSetFile == null)
{
SendUnableToOpenRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist);
return;
}
try
{
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
dte.ItemOperations.OpenFile(ruleSetFile);
}
catch (Exception e)
{
SendUnableToOpenRuleSetNotification(workspace, e.Message);
}
}
}
}
private void SetSeverityHandler(object sender, EventArgs args)
{
var selectedItem = (MenuCommand)sender;
var selectedAction = MapSelectedItemToReportDiagnostic(selectedItem);
if (!selectedAction.HasValue)
{
return;
}
var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl;
if (workspace == null)
{
return;
}
foreach (var selectedDiagnostic in _tracker.SelectedDiagnosticItems)
{
var projectId = selectedDiagnostic.ProjectId;
var pathToRuleSet = workspace.TryGetRuleSetPathForProject(projectId);
var project = workspace.CurrentSolution.GetProject(projectId);
var pathToAnalyzerConfigDoc = project?.TryGetAnalyzerConfigPathForProjectConfiguration();
if (pathToRuleSet == null && pathToAnalyzerConfigDoc == null)
{
SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist);
continue;
}
var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
var uiThreadOperationExecutor = componentModel.GetService<IUIThreadOperationExecutor>();
var editHandlerService = componentModel.GetService<ICodeActionEditHandlerService>();
try
{
var envDteProject = workspace.TryGetDTEProject(projectId);
if (pathToRuleSet == null || SdkUiUtilities.IsBuiltInRuleSet(pathToRuleSet, _serviceProvider))
{
// If project is using the default built-in ruleset or no ruleset, then prefer .editorconfig for severity configuration.
if (pathToAnalyzerConfigDoc != null)
{
uiThreadOperationExecutor.Execute(
title: ServicesVSResources.Updating_severity,
defaultDescription: "",
allowCancellation: true,
showProgress: true,
action: context =>
{
var scope = context.AddScope(allowCancellation: true, ServicesVSResources.Updating_severity);
var newSolution = selectedDiagnostic.GetSolutionWithUpdatedAnalyzerConfigSeverityAsync(selectedAction.Value, project, context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken);
var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution));
editHandlerService.Apply(
_workspace,
fromDocument: null,
operations: operations,
title: ServicesVSResources.Updating_severity,
progressTracker: new UIThreadOperationContextProgressTracker(scope),
cancellationToken: context.UserCancellationToken);
});
continue;
}
// Otherwise, fall back to using ruleset.
if (pathToRuleSet == null)
{
SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist);
continue;
}
pathToRuleSet = CreateCopyOfRuleSetForProject(pathToRuleSet, envDteProject);
if (pathToRuleSet == null)
{
SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.Could_not_create_a_rule_set_for_project_0, envDteProject.Name));
continue;
}
var fileInfo = new FileInfo(pathToRuleSet);
fileInfo.IsReadOnly = false;
}
uiThreadOperationExecutor.Execute(
title: SolutionExplorerShim.Rule_Set,
defaultDescription: string.Format(SolutionExplorerShim.Checking_out_0_for_editing, Path.GetFileName(pathToRuleSet)),
allowCancellation: false,
showProgress: false,
action: c =>
{
if (envDteProject.DTE.SourceControl.IsItemUnderSCC(pathToRuleSet))
{
envDteProject.DTE.SourceControl.CheckOutItem(pathToRuleSet);
}
});
selectedDiagnostic.SetRuleSetSeverity(selectedAction.Value, pathToRuleSet);
}
catch (Exception e)
{
SendUnableToUpdateRuleSetNotification(workspace, e.Message);
}
}
}
private void OpenDiagnosticHelpLinkHandler(object sender, EventArgs e)
{
if (_tracker.SelectedDiagnosticItems.Length != 1)
{
return;
}
var uri = _tracker.SelectedDiagnosticItems[0].GetHelpLink();
if (uri != null)
{
VisualStudioNavigateToLinkService.StartBrowser(uri);
}
}
private void SetActiveRuleSetHandler(object sender, EventArgs e)
{
if (_tracker.SelectedHierarchy.TryGetProject(out var project) &&
_tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out var ruleSetFileFullPath))
{
var projectDirectoryFullPath = Path.GetDirectoryName(project.FullName);
var ruleSetFileRelativePath = PathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath);
UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath);
}
}
private string CreateCopyOfRuleSetForProject(string pathToRuleSet, EnvDTE.Project envDteProject)
{
var fileName = GetNewRuleSetFileNameForProject(envDteProject);
var projectDirectory = Path.GetDirectoryName(envDteProject.FullName);
var fullFilePath = Path.Combine(projectDirectory, fileName);
File.Copy(pathToRuleSet, fullFilePath);
UpdateProjectConfigurationsToUseRuleSetFile(envDteProject, fileName);
envDteProject.ProjectItems.AddFromFile(fullFilePath);
return fullFilePath;
}
private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName)
{
foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager)
{
var properties = config.Properties;
try
{
var codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet");
if (codeAnalysisRuleSetFileProperty != null)
{
codeAnalysisRuleSetFileProperty.Value = fileName;
}
}
catch (ArgumentException)
{
// Unfortunately the properties collection sometimes throws an ArgumentException
// instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet.
// Ignore it and move on.
}
}
}
private string GetNewRuleSetFileNameForProject(EnvDTE.Project envDteProject)
{
var projectName = envDteProject.Name;
var projectItemNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ProjectItem item in envDteProject.ProjectItems)
{
projectItemNames.Add(item.Name);
}
var ruleSetName = projectName + ".ruleset";
if (!projectItemNames.Contains(ruleSetName))
{
return ruleSetName;
}
for (var i = 1; i < int.MaxValue; i++)
{
ruleSetName = projectName + i + ".ruleset";
if (!projectItemNames.Contains(ruleSetName))
{
return ruleSetName;
}
}
return null;
}
private static ReportDiagnostic? MapSelectedItemToReportDiagnostic(MenuCommand selectedItem)
{
ReportDiagnostic? selectedAction = null;
if (selectedItem.CommandID.Guid == Guids.RoslynGroupId)
{
switch (selectedItem.CommandID.ID)
{
case ID.RoslynCommands.SetSeverityDefault:
selectedAction = ReportDiagnostic.Default;
break;
case ID.RoslynCommands.SetSeverityError:
selectedAction = ReportDiagnostic.Error;
break;
case ID.RoslynCommands.SetSeverityWarning:
selectedAction = ReportDiagnostic.Warn;
break;
case ID.RoslynCommands.SetSeverityInfo:
selectedAction = ReportDiagnostic.Info;
break;
case ID.RoslynCommands.SetSeverityHidden:
selectedAction = ReportDiagnostic.Hidden;
break;
case ID.RoslynCommands.SetSeverityNone:
selectedAction = ReportDiagnostic.Suppress;
break;
default:
selectedAction = null;
break;
}
}
return selectedAction;
}
private void SendUnableToOpenRuleSetNotification(Workspace workspace, string message)
{
SendErrorNotification(
workspace,
SolutionExplorerShim.The_rule_set_file_could_not_be_opened,
message);
}
private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message)
{
SendErrorNotification(
workspace,
SolutionExplorerShim.The_rule_set_file_could_not_be_updated,
message);
}
private void SendErrorNotification(Workspace workspace, string message1, string message2)
{
var notificationService = workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(message1 + Environment.NewLine + Environment.NewLine + message2, severity: NotificationSeverity.Error);
}
int IVsUpdateSolutionEvents.UpdateSolution_Begin(ref int pfCancelUpdate)
{
_allowProjectSystemOperations = false;
UpdateOtherMenuItemsEnabled();
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand)
{
_allowProjectSystemOperations = true;
UpdateOtherMenuItemsEnabled();
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.UpdateSolution_StartUpdate(ref int pfCancelUpdate)
{
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.UpdateSolution_Cancel()
{
_allowProjectSystemOperations = true;
UpdateOtherMenuItemsEnabled();
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy)
{
return VSConstants.S_OK;
}
private Workspace TryGetWorkspace()
{
if (_workspace == null)
{
var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
_workspace = componentModel.DefaultExportProvider.GetExportedValueOrDefault<VisualStudioWorkspace>();
}
return _workspace;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.CodeAnalysis;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSLangProj140;
using Workspace = Microsoft.CodeAnalysis.Workspace;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
[Export]
internal class AnalyzersCommandHandler : IAnalyzersCommandHandler, IVsUpdateSolutionEvents
{
private readonly AnalyzerItemsTracker _tracker;
private readonly AnalyzerReferenceManager _analyzerReferenceManager;
private readonly IServiceProvider _serviceProvider;
private ContextMenuController _analyzerFolderContextMenuController;
private ContextMenuController _analyzerContextMenuController;
private ContextMenuController _diagnosticContextMenuController;
// Analyzers folder context menu items
private MenuCommand _addMenuItem;
// Analyzer context menu items
private MenuCommand _removeMenuItem;
// Diagnostic context menu items
private MenuCommand _setSeverityDefaultMenuItem;
private MenuCommand _setSeverityErrorMenuItem;
private MenuCommand _setSeverityWarningMenuItem;
private MenuCommand _setSeverityInfoMenuItem;
private MenuCommand _setSeverityHiddenMenuItem;
private MenuCommand _setSeverityNoneMenuItem;
private MenuCommand _openHelpLinkMenuItem;
// Other menu items
private MenuCommand _projectAddMenuItem;
private MenuCommand _projectContextAddMenuItem;
private MenuCommand _referencesContextAddMenuItem;
private MenuCommand _setActiveRuleSetMenuItem;
private Workspace _workspace;
private bool _allowProjectSystemOperations = true;
private bool _initialized;
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public AnalyzersCommandHandler(
AnalyzerItemsTracker tracker,
AnalyzerReferenceManager analyzerReferenceManager,
[Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
{
_tracker = tracker;
_analyzerReferenceManager = analyzerReferenceManager;
_serviceProvider = serviceProvider;
}
/// <summary>
/// Hook up the context menu handlers.
/// </summary>
public void Initialize(IMenuCommandService menuCommandService)
{
if (menuCommandService != null)
{
// Analyzers folder context menu items
_addMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.AddAnalyzer, AddAnalyzerHandler);
_ = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenRuleSet, OpenRuleSetHandler);
// Analyzer context menu items
_removeMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.RemoveAnalyzer, RemoveAnalyzerHandler);
// Diagnostic context menu items
_setSeverityDefaultMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityDefault, SetSeverityHandler);
_setSeverityErrorMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityError, SetSeverityHandler);
_setSeverityWarningMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityWarning, SetSeverityHandler);
_setSeverityInfoMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityInfo, SetSeverityHandler);
_setSeverityHiddenMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityHidden, SetSeverityHandler);
_setSeverityNoneMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityNone, SetSeverityHandler);
_openHelpLinkMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenDiagnosticHelpLink, OpenDiagnosticHelpLinkHandler);
// Other menu items
_projectAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectAddAnalyzer, AddAnalyzerHandler);
_projectContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectContextAddAnalyzer, AddAnalyzerHandler);
_referencesContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ReferencesContextAddAnalyzer, AddAnalyzerHandler);
_setActiveRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetActiveRuleSet, SetActiveRuleSetHandler);
UpdateOtherMenuItemsVisibility();
if (_tracker != null)
{
_tracker.SelectedHierarchyItemChanged += SelectedHierarchyItemChangedHandler;
}
var buildManager = (IVsSolutionBuildManager)_serviceProvider.GetService(typeof(SVsSolutionBuildManager));
buildManager.AdviseUpdateSolutionEvents(this, out var cookie);
_initialized = true;
}
}
public IContextMenuController AnalyzerFolderContextMenuController
{
get
{
if (_analyzerFolderContextMenuController == null)
{
_analyzerFolderContextMenuController = new ContextMenuController(
ID.RoslynCommands.AnalyzerFolderContextMenu,
ShouldShowAnalyzerFolderContextMenu,
UpdateAnalyzerFolderContextMenu);
}
return _analyzerFolderContextMenuController;
}
}
private bool ShouldShowAnalyzerFolderContextMenu(IEnumerable<object> items)
{
return items.Count() == 1;
}
private void UpdateAnalyzerFolderContextMenu()
{
if (_addMenuItem != null)
{
_addMenuItem.Visible = SelectedProjectSupportsAnalyzers();
_addMenuItem.Enabled = _allowProjectSystemOperations;
}
}
public IContextMenuController AnalyzerContextMenuController
{
get
{
if (_analyzerContextMenuController == null)
{
_analyzerContextMenuController = new ContextMenuController(
ID.RoslynCommands.AnalyzerContextMenu,
ShouldShowAnalyzerContextMenu,
UpdateAnalyzerContextMenu);
}
return _analyzerContextMenuController;
}
}
private bool ShouldShowAnalyzerContextMenu(IEnumerable<object> items)
{
return items.All(item => item is AnalyzerItem);
}
private void UpdateAnalyzerContextMenu()
{
if (_removeMenuItem != null)
{
_removeMenuItem.Enabled = _allowProjectSystemOperations;
}
}
public IContextMenuController DiagnosticContextMenuController
{
get
{
if (_diagnosticContextMenuController == null)
{
_diagnosticContextMenuController = new ContextMenuController(
ID.RoslynCommands.DiagnosticContextMenu,
ShouldShowDiagnosticContextMenu,
UpdateDiagnosticContextMenu);
}
return _diagnosticContextMenuController;
}
}
private bool ShouldShowDiagnosticContextMenu(IEnumerable<object> items)
{
return _initialized && items.All(item => item is DiagnosticItem);
}
private void UpdateDiagnosticContextMenu()
{
Debug.Assert(_initialized);
UpdateSeverityMenuItemsChecked();
UpdateSeverityMenuItemsEnabled();
UpdateOpenHelpLinkMenuItemVisibility();
}
private MenuCommand AddCommandHandler(IMenuCommandService menuCommandService, int roslynCommand, EventHandler handler)
{
var commandID = new CommandID(Guids.RoslynGroupId, roslynCommand);
var menuCommand = new MenuCommand(handler, commandID);
menuCommandService.AddCommand(menuCommand);
return menuCommand;
}
private void SelectedHierarchyItemChangedHandler(object sender, EventArgs e)
{
UpdateOtherMenuItemsVisibility();
}
private void UpdateOtherMenuItemsVisibility()
{
var selectedProjectSupportsAnalyzers = SelectedProjectSupportsAnalyzers();
_projectAddMenuItem.Visible = selectedProjectSupportsAnalyzers;
_projectContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedItemId == VSConstants.VSITEMID_ROOT;
_referencesContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers;
_setActiveRuleSetMenuItem.Visible = selectedProjectSupportsAnalyzers &&
_tracker.SelectedHierarchy.TryGetItemName(_tracker.SelectedItemId, out var itemName) &&
Path.GetExtension(itemName).Equals(".ruleset", StringComparison.OrdinalIgnoreCase);
}
private void UpdateOtherMenuItemsEnabled()
{
_projectAddMenuItem.Enabled = _allowProjectSystemOperations;
_projectContextAddMenuItem.Enabled = _allowProjectSystemOperations;
_referencesContextAddMenuItem.Enabled = _allowProjectSystemOperations;
_removeMenuItem.Enabled = _allowProjectSystemOperations;
}
private void UpdateOpenHelpLinkMenuItemVisibility()
{
_openHelpLinkMenuItem.Visible = _tracker.SelectedDiagnosticItems.Length == 1 &&
_tracker.SelectedDiagnosticItems[0].GetHelpLink() != null;
}
private void UpdateSeverityMenuItemsChecked()
{
_setSeverityDefaultMenuItem.Checked = false;
_setSeverityErrorMenuItem.Checked = false;
_setSeverityWarningMenuItem.Checked = false;
_setSeverityInfoMenuItem.Checked = false;
_setSeverityHiddenMenuItem.Checked = false;
_setSeverityNoneMenuItem.Checked = false;
var workspace = TryGetWorkspace() as VisualStudioWorkspace;
if (workspace == null)
{
return;
}
var selectedItemSeverities = new HashSet<ReportDiagnostic>();
var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.ProjectId);
foreach (var group in groups)
{
var project = workspace.CurrentSolution.GetProject(group.Key);
if (project == null)
{
continue;
}
var analyzerConfigOptions = project.GetAnalyzerConfigOptions();
foreach (var diagnosticItem in group)
{
var severity = diagnosticItem.Descriptor.GetEffectiveSeverity(project.CompilationOptions, analyzerConfigOptions);
selectedItemSeverities.Add(severity);
}
}
if (selectedItemSeverities.Count != 1)
{
return;
}
switch (selectedItemSeverities.Single())
{
case ReportDiagnostic.Default:
_setSeverityDefaultMenuItem.Checked = true;
break;
case ReportDiagnostic.Error:
_setSeverityErrorMenuItem.Checked = true;
break;
case ReportDiagnostic.Warn:
_setSeverityWarningMenuItem.Checked = true;
break;
case ReportDiagnostic.Info:
_setSeverityInfoMenuItem.Checked = true;
break;
case ReportDiagnostic.Hidden:
_setSeverityHiddenMenuItem.Checked = true;
break;
case ReportDiagnostic.Suppress:
_setSeverityNoneMenuItem.Checked = true;
break;
default:
break;
}
}
private void UpdateSeverityMenuItemsEnabled()
{
var configurable = !_tracker.SelectedDiagnosticItems.Any(item => item.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.NotConfigurable));
_setSeverityDefaultMenuItem.Enabled = configurable;
_setSeverityErrorMenuItem.Enabled = configurable;
_setSeverityWarningMenuItem.Enabled = configurable;
_setSeverityInfoMenuItem.Enabled = configurable;
_setSeverityHiddenMenuItem.Enabled = configurable;
_setSeverityNoneMenuItem.Enabled = configurable;
}
private bool SelectedProjectSupportsAnalyzers()
{
return _tracker != null &&
_tracker.SelectedHierarchy != null &&
_tracker.SelectedHierarchy.TryGetProject(out var project) &&
project.Object is VSProject3;
}
/// <summary>
/// Handler for "Add Analyzer..." context menu on Analyzers folder node.
/// </summary>
internal void AddAnalyzerHandler(object sender, EventArgs args)
{
if (_analyzerReferenceManager != null)
{
_analyzerReferenceManager.ShowDialog();
}
}
/// <summary>
/// Handler for "Remove" context menu on individual Analyzer items.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
internal void RemoveAnalyzerHandler(object sender, EventArgs args)
{
foreach (var item in _tracker.SelectedAnalyzerItems)
{
item.Remove();
}
}
internal void OpenRuleSetHandler(object sender, EventArgs args)
{
if (_tracker.SelectedFolder != null &&
_serviceProvider != null)
{
var workspace = _tracker.SelectedFolder.Workspace as VisualStudioWorkspace;
var projectId = _tracker.SelectedFolder.ProjectId;
if (workspace != null)
{
var ruleSetFile = workspace.TryGetRuleSetPathForProject(projectId);
if (ruleSetFile == null)
{
SendUnableToOpenRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist);
return;
}
try
{
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
dte.ItemOperations.OpenFile(ruleSetFile);
}
catch (Exception e)
{
SendUnableToOpenRuleSetNotification(workspace, e.Message);
}
}
}
}
private void SetSeverityHandler(object sender, EventArgs args)
{
var selectedItem = (MenuCommand)sender;
var selectedAction = MapSelectedItemToReportDiagnostic(selectedItem);
if (!selectedAction.HasValue)
{
return;
}
var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl;
if (workspace == null)
{
return;
}
foreach (var selectedDiagnostic in _tracker.SelectedDiagnosticItems)
{
var projectId = selectedDiagnostic.ProjectId;
var pathToRuleSet = workspace.TryGetRuleSetPathForProject(projectId);
var project = workspace.CurrentSolution.GetProject(projectId);
var pathToAnalyzerConfigDoc = project?.TryGetAnalyzerConfigPathForProjectConfiguration();
if (pathToRuleSet == null && pathToAnalyzerConfigDoc == null)
{
SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist);
continue;
}
var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
var uiThreadOperationExecutor = componentModel.GetService<IUIThreadOperationExecutor>();
var editHandlerService = componentModel.GetService<ICodeActionEditHandlerService>();
try
{
var envDteProject = workspace.TryGetDTEProject(projectId);
if (pathToRuleSet == null || SdkUiUtilities.IsBuiltInRuleSet(pathToRuleSet, _serviceProvider))
{
// If project is using the default built-in ruleset or no ruleset, then prefer .editorconfig for severity configuration.
if (pathToAnalyzerConfigDoc != null)
{
uiThreadOperationExecutor.Execute(
title: ServicesVSResources.Updating_severity,
defaultDescription: "",
allowCancellation: true,
showProgress: true,
action: context =>
{
var scope = context.AddScope(allowCancellation: true, ServicesVSResources.Updating_severity);
var newSolution = selectedDiagnostic.GetSolutionWithUpdatedAnalyzerConfigSeverityAsync(selectedAction.Value, project, context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken);
var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution));
editHandlerService.Apply(
_workspace,
fromDocument: null,
operations: operations,
title: ServicesVSResources.Updating_severity,
progressTracker: new UIThreadOperationContextProgressTracker(scope),
cancellationToken: context.UserCancellationToken);
});
continue;
}
// Otherwise, fall back to using ruleset.
if (pathToRuleSet == null)
{
SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist);
continue;
}
pathToRuleSet = CreateCopyOfRuleSetForProject(pathToRuleSet, envDteProject);
if (pathToRuleSet == null)
{
SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.Could_not_create_a_rule_set_for_project_0, envDteProject.Name));
continue;
}
var fileInfo = new FileInfo(pathToRuleSet);
fileInfo.IsReadOnly = false;
}
uiThreadOperationExecutor.Execute(
title: SolutionExplorerShim.Rule_Set,
defaultDescription: string.Format(SolutionExplorerShim.Checking_out_0_for_editing, Path.GetFileName(pathToRuleSet)),
allowCancellation: false,
showProgress: false,
action: c =>
{
if (envDteProject.DTE.SourceControl.IsItemUnderSCC(pathToRuleSet))
{
envDteProject.DTE.SourceControl.CheckOutItem(pathToRuleSet);
}
});
selectedDiagnostic.SetRuleSetSeverity(selectedAction.Value, pathToRuleSet);
}
catch (Exception e)
{
SendUnableToUpdateRuleSetNotification(workspace, e.Message);
}
}
}
private void OpenDiagnosticHelpLinkHandler(object sender, EventArgs e)
{
if (_tracker.SelectedDiagnosticItems.Length != 1)
{
return;
}
var uri = _tracker.SelectedDiagnosticItems[0].GetHelpLink();
if (uri != null)
{
VisualStudioNavigateToLinkService.StartBrowser(uri);
}
}
private void SetActiveRuleSetHandler(object sender, EventArgs e)
{
if (_tracker.SelectedHierarchy.TryGetProject(out var project) &&
_tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out var ruleSetFileFullPath))
{
var projectDirectoryFullPath = Path.GetDirectoryName(project.FullName);
var ruleSetFileRelativePath = PathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath);
UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath);
}
}
private string CreateCopyOfRuleSetForProject(string pathToRuleSet, EnvDTE.Project envDteProject)
{
var fileName = GetNewRuleSetFileNameForProject(envDteProject);
var projectDirectory = Path.GetDirectoryName(envDteProject.FullName);
var fullFilePath = Path.Combine(projectDirectory, fileName);
File.Copy(pathToRuleSet, fullFilePath);
UpdateProjectConfigurationsToUseRuleSetFile(envDteProject, fileName);
envDteProject.ProjectItems.AddFromFile(fullFilePath);
return fullFilePath;
}
private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName)
{
foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager)
{
var properties = config.Properties;
try
{
var codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet");
if (codeAnalysisRuleSetFileProperty != null)
{
codeAnalysisRuleSetFileProperty.Value = fileName;
}
}
catch (ArgumentException)
{
// Unfortunately the properties collection sometimes throws an ArgumentException
// instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet.
// Ignore it and move on.
}
}
}
private string GetNewRuleSetFileNameForProject(EnvDTE.Project envDteProject)
{
var projectName = envDteProject.Name;
var projectItemNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ProjectItem item in envDteProject.ProjectItems)
{
projectItemNames.Add(item.Name);
}
var ruleSetName = projectName + ".ruleset";
if (!projectItemNames.Contains(ruleSetName))
{
return ruleSetName;
}
for (var i = 1; i < int.MaxValue; i++)
{
ruleSetName = projectName + i + ".ruleset";
if (!projectItemNames.Contains(ruleSetName))
{
return ruleSetName;
}
}
return null;
}
private static ReportDiagnostic? MapSelectedItemToReportDiagnostic(MenuCommand selectedItem)
{
ReportDiagnostic? selectedAction = null;
if (selectedItem.CommandID.Guid == Guids.RoslynGroupId)
{
switch (selectedItem.CommandID.ID)
{
case ID.RoslynCommands.SetSeverityDefault:
selectedAction = ReportDiagnostic.Default;
break;
case ID.RoslynCommands.SetSeverityError:
selectedAction = ReportDiagnostic.Error;
break;
case ID.RoslynCommands.SetSeverityWarning:
selectedAction = ReportDiagnostic.Warn;
break;
case ID.RoslynCommands.SetSeverityInfo:
selectedAction = ReportDiagnostic.Info;
break;
case ID.RoslynCommands.SetSeverityHidden:
selectedAction = ReportDiagnostic.Hidden;
break;
case ID.RoslynCommands.SetSeverityNone:
selectedAction = ReportDiagnostic.Suppress;
break;
default:
selectedAction = null;
break;
}
}
return selectedAction;
}
private void SendUnableToOpenRuleSetNotification(Workspace workspace, string message)
{
SendErrorNotification(
workspace,
SolutionExplorerShim.The_rule_set_file_could_not_be_opened,
message);
}
private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message)
{
SendErrorNotification(
workspace,
SolutionExplorerShim.The_rule_set_file_could_not_be_updated,
message);
}
private void SendErrorNotification(Workspace workspace, string message1, string message2)
{
var notificationService = workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(message1 + Environment.NewLine + Environment.NewLine + message2, severity: NotificationSeverity.Error);
}
int IVsUpdateSolutionEvents.UpdateSolution_Begin(ref int pfCancelUpdate)
{
_allowProjectSystemOperations = false;
UpdateOtherMenuItemsEnabled();
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand)
{
_allowProjectSystemOperations = true;
UpdateOtherMenuItemsEnabled();
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.UpdateSolution_StartUpdate(ref int pfCancelUpdate)
{
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.UpdateSolution_Cancel()
{
_allowProjectSystemOperations = true;
UpdateOtherMenuItemsEnabled();
return VSConstants.S_OK;
}
int IVsUpdateSolutionEvents.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy)
{
return VSConstants.S_OK;
}
private Workspace TryGetWorkspace()
{
if (_workspace == null)
{
var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
_workspace = componentModel.DefaultExportProvider.GetExportedValueOrDefault<VisualStudioWorkspace>();
}
return _workspace;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/Core/Portable/Serialization/IObjectWritable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Roslyn.Utilities
{
/// <summary>
/// Objects that implement this interface know how to write their contents to an <see cref="ObjectWriter"/>,
/// so they can be reconstructed later by an <see cref="ObjectReader"/>.
/// </summary>
internal interface IObjectWritable
{
void WriteTo(ObjectWriter writer);
/// <summary>
/// Returns 'true' when the same instance could be used more than once.
/// Instances that return 'false' should not be tracked for the purpose
/// of de-duplication while serializing/deserializing.
/// </summary>
bool ShouldReuseInSerialization { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Roslyn.Utilities
{
/// <summary>
/// Objects that implement this interface know how to write their contents to an <see cref="ObjectWriter"/>,
/// so they can be reconstructed later by an <see cref="ObjectReader"/>.
/// </summary>
internal interface IObjectWritable
{
void WriteTo(ObjectWriter writer);
/// <summary>
/// Returns 'true' when the same instance could be used more than once.
/// Instances that return 'false' should not be tracked for the purpose
/// of de-duplication while serializing/deserializing.
/// </summary>
bool ShouldReuseInSerialization { get; }
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SymbolUsageInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Provides information about the way a particular symbol is being used at a symbol reference node.
/// For namespaces and types, this corresponds to values from <see cref="TypeOrNamespaceUsageInfo"/>.
/// For methods, fields, properties, events, locals and parameters, this corresponds to values from <see cref="ValueUsageInfo"/>.
/// </summary>
[DataContract]
internal readonly struct SymbolUsageInfo : IEquatable<SymbolUsageInfo>
{
public static readonly SymbolUsageInfo None = Create(ValueUsageInfo.None);
[DataMember(Order = 0)]
public ValueUsageInfo? ValueUsageInfoOpt { get; }
[DataMember(Order = 1)]
public TypeOrNamespaceUsageInfo? TypeOrNamespaceUsageInfoOpt { get; }
// Must be public since it's used for deserialization.
public SymbolUsageInfo(ValueUsageInfo? valueUsageInfoOpt, TypeOrNamespaceUsageInfo? typeOrNamespaceUsageInfoOpt)
{
Debug.Assert(valueUsageInfoOpt.HasValue ^ typeOrNamespaceUsageInfoOpt.HasValue);
ValueUsageInfoOpt = valueUsageInfoOpt;
TypeOrNamespaceUsageInfoOpt = typeOrNamespaceUsageInfoOpt;
}
public static SymbolUsageInfo Create(ValueUsageInfo valueUsageInfo)
=> new(valueUsageInfo, typeOrNamespaceUsageInfoOpt: null);
public static SymbolUsageInfo Create(TypeOrNamespaceUsageInfo typeOrNamespaceUsageInfo)
=> new(valueUsageInfoOpt: null, typeOrNamespaceUsageInfo);
public bool IsReadFrom()
=> ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsReadFrom();
public bool IsWrittenTo()
=> ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsWrittenTo();
public bool IsNameOnly()
=> ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsNameOnly();
public override bool Equals(object? obj)
=> obj is SymbolUsageInfo && Equals((SymbolUsageInfo)obj);
public bool Equals(SymbolUsageInfo other)
{
if (ValueUsageInfoOpt.HasValue)
{
return other.ValueUsageInfoOpt.HasValue &&
ValueUsageInfoOpt.Value == other.ValueUsageInfoOpt.Value;
}
else
{
RoslynDebug.Assert(TypeOrNamespaceUsageInfoOpt.HasValue);
return other.TypeOrNamespaceUsageInfoOpt.HasValue &&
TypeOrNamespaceUsageInfoOpt.Value == other.TypeOrNamespaceUsageInfoOpt.Value;
}
}
public override int GetHashCode()
=> Hash.Combine(ValueUsageInfoOpt?.GetHashCode() ?? 0, TypeOrNamespaceUsageInfoOpt?.GetHashCode() ?? 0);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Provides information about the way a particular symbol is being used at a symbol reference node.
/// For namespaces and types, this corresponds to values from <see cref="TypeOrNamespaceUsageInfo"/>.
/// For methods, fields, properties, events, locals and parameters, this corresponds to values from <see cref="ValueUsageInfo"/>.
/// </summary>
[DataContract]
internal readonly struct SymbolUsageInfo : IEquatable<SymbolUsageInfo>
{
public static readonly SymbolUsageInfo None = Create(ValueUsageInfo.None);
[DataMember(Order = 0)]
public ValueUsageInfo? ValueUsageInfoOpt { get; }
[DataMember(Order = 1)]
public TypeOrNamespaceUsageInfo? TypeOrNamespaceUsageInfoOpt { get; }
// Must be public since it's used for deserialization.
public SymbolUsageInfo(ValueUsageInfo? valueUsageInfoOpt, TypeOrNamespaceUsageInfo? typeOrNamespaceUsageInfoOpt)
{
Debug.Assert(valueUsageInfoOpt.HasValue ^ typeOrNamespaceUsageInfoOpt.HasValue);
ValueUsageInfoOpt = valueUsageInfoOpt;
TypeOrNamespaceUsageInfoOpt = typeOrNamespaceUsageInfoOpt;
}
public static SymbolUsageInfo Create(ValueUsageInfo valueUsageInfo)
=> new(valueUsageInfo, typeOrNamespaceUsageInfoOpt: null);
public static SymbolUsageInfo Create(TypeOrNamespaceUsageInfo typeOrNamespaceUsageInfo)
=> new(valueUsageInfoOpt: null, typeOrNamespaceUsageInfo);
public bool IsReadFrom()
=> ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsReadFrom();
public bool IsWrittenTo()
=> ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsWrittenTo();
public bool IsNameOnly()
=> ValueUsageInfoOpt.HasValue && ValueUsageInfoOpt.Value.IsNameOnly();
public override bool Equals(object? obj)
=> obj is SymbolUsageInfo && Equals((SymbolUsageInfo)obj);
public bool Equals(SymbolUsageInfo other)
{
if (ValueUsageInfoOpt.HasValue)
{
return other.ValueUsageInfoOpt.HasValue &&
ValueUsageInfoOpt.Value == other.ValueUsageInfoOpt.Value;
}
else
{
RoslynDebug.Assert(TypeOrNamespaceUsageInfoOpt.HasValue);
return other.TypeOrNamespaceUsageInfoOpt.HasValue &&
TypeOrNamespaceUsageInfoOpt.Value == other.TypeOrNamespaceUsageInfoOpt.Value;
}
}
public override int GetHashCode()
=> Hash.Combine(ValueUsageInfoOpt?.GetHashCode() ?? 0, TypeOrNamespaceUsageInfoOpt?.GetHashCode() ?? 0);
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/RealParserTests/CLibraryShim/CLibraryShim.vcxproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{D8C0BD38-F641-4D8E-A2E0-8F89F30531B2}</ProjectGuid>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<Keyword>ManagedCProj</Keyword>
<RootNamespace>CLibraryShim</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile />
<PrecompiledHeaderOutputFile />
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PreprocessorDefinitions>WIN32;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="CLibraryShim.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="AssemblyInfo.cpp" />
<ClCompile Include="CLibraryShim.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{D8C0BD38-F641-4D8E-A2E0-8F89F30531B2}</ProjectGuid>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<Keyword>ManagedCProj</Keyword>
<RootNamespace>CLibraryShim</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CLRSupport>true</CLRSupport>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile />
<PrecompiledHeaderOutputFile />
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PreprocessorDefinitions>WIN32;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies />
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="CLibraryShim.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="AssemblyInfo.cpp" />
<ClCompile Include="CLibraryShim.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project> | -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpFrameDecoder : FrameDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol>
{
public CSharpFrameDecoder()
: base(CSharpInstructionDecoder.Instance)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpFrameDecoder : FrameDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol>
{
public CSharpFrameDecoder()
: base(CSharpInstructionDecoder.Instance)
{
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTokenListTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class SyntaxTokenListTests : CSharpTestBase
{
[Fact]
public void TestEquality()
{
var node1 = SyntaxFactory.ReturnStatement();
EqualityTesting.AssertEqual(default(SyntaxTokenList), default(SyntaxTokenList));
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0));
// index is considered
EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0));
// position not considered:
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0));
}
[Fact]
public void TestReverse_Equality()
{
var node1 = SyntaxFactory.ReturnStatement();
EqualityTesting.AssertEqual(default(SyntaxTokenList).Reverse(), default(SyntaxTokenList).Reverse());
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse());
// index is considered
EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse());
// position not considered:
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse());
}
[Fact]
public void TestEnumeratorEquality()
{
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).GetHashCode());
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).Equals(default(SyntaxTokenList.Enumerator)));
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).GetHashCode());
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).Equals(default(SyntaxTokenList.Reversed.Enumerator)));
}
[Fact]
public void TestAddInsertRemoveReplace()
{
var list = SyntaxFactory.TokenList(SyntaxFactory.ParseToken("A "), SyntaxFactory.ParseToken("B "), SyntaxFactory.ParseToken("C "));
Assert.Equal(3, list.Count);
Assert.Equal("A", list[0].ToString());
Assert.Equal("B", list[1].ToString());
Assert.Equal("C", list[2].ToString());
Assert.Equal("A B C ", list.ToFullString());
var elementA = list[0];
var elementB = list[1];
var elementC = list[2];
Assert.Equal(0, list.IndexOf(elementA));
Assert.Equal(1, list.IndexOf(elementB));
Assert.Equal(2, list.IndexOf(elementC));
var tokenD = SyntaxFactory.ParseToken("D ");
var tokenE = SyntaxFactory.ParseToken("E ");
var newList = list.Add(tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("D A B C ", newList.ToFullString());
newList = list.Insert(1, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A D B C ", newList.ToFullString());
newList = list.Insert(2, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B D C ", newList.ToFullString());
newList = list.Insert(3, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("D E A B C ", newList.ToFullString());
newList = list.InsertRange(1, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A D E B C ", newList.ToFullString());
newList = list.InsertRange(2, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B D E C ", newList.ToFullString());
newList = list.InsertRange(3, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.RemoveAt(0);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.RemoveAt(list.Count - 1);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Remove(elementA);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.Remove(elementB);
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.Remove(elementC);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Replace(elementA, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("D B C ", newList.ToFullString());
newList = list.Replace(elementB, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A D C ", newList.ToFullString());
newList = list.Replace(elementC, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A B D ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new[] { tokenD, tokenE });
Assert.Equal(4, newList.Count);
Assert.Equal("D E B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new[] { tokenD, tokenE });
Assert.Equal(4, newList.Count);
Assert.Equal("A D E C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new[] { tokenD, tokenE });
Assert.Equal(4, newList.Count);
Assert.Equal("A B D E ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new SyntaxToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new SyntaxToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new SyntaxToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null));
Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxToken>)null));
}
[Fact]
public void TestAddInsertRemoveReplaceOnEmptyList()
{
DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.TokenList());
DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxTokenList));
}
private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTokenList list)
{
Assert.Equal(0, list.Count);
var tokenD = SyntaxFactory.ParseToken("D ");
var tokenE = SyntaxFactory.ParseToken("E ");
var newList = list.Add(tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, tokenE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, tokenE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Remove(tokenD);
Assert.Equal(0, newList.Count);
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(tokenD, tokenE));
Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(tokenD, new[] { tokenE }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null));
}
[Fact]
public void Extensions()
{
var list = SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.SizeOfKeyword),
SyntaxFactory.Literal("x"),
SyntaxFactory.Token(SyntaxKind.DotToken));
Assert.Equal(0, list.IndexOf(SyntaxKind.SizeOfKeyword));
Assert.True(list.Any(SyntaxKind.SizeOfKeyword));
Assert.Equal(1, list.IndexOf(SyntaxKind.StringLiteralToken));
Assert.True(list.Any(SyntaxKind.StringLiteralToken));
Assert.Equal(2, list.IndexOf(SyntaxKind.DotToken));
Assert.True(list.Any(SyntaxKind.DotToken));
Assert.Equal(-1, list.IndexOf(SyntaxKind.NullKeyword));
Assert.False(list.Any(SyntaxKind.NullKeyword));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class SyntaxTokenListTests : CSharpTestBase
{
[Fact]
public void TestEquality()
{
var node1 = SyntaxFactory.ReturnStatement();
EqualityTesting.AssertEqual(default(SyntaxTokenList), default(SyntaxTokenList));
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0));
// index is considered
EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0));
// position not considered:
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0));
}
[Fact]
public void TestReverse_Equality()
{
var node1 = SyntaxFactory.ReturnStatement();
EqualityTesting.AssertEqual(default(SyntaxTokenList).Reverse(), default(SyntaxTokenList).Reverse());
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse());
// index is considered
EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse());
// position not considered:
EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse());
}
[Fact]
public void TestEnumeratorEquality()
{
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).GetHashCode());
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).Equals(default(SyntaxTokenList.Enumerator)));
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).GetHashCode());
Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).Equals(default(SyntaxTokenList.Reversed.Enumerator)));
}
[Fact]
public void TestAddInsertRemoveReplace()
{
var list = SyntaxFactory.TokenList(SyntaxFactory.ParseToken("A "), SyntaxFactory.ParseToken("B "), SyntaxFactory.ParseToken("C "));
Assert.Equal(3, list.Count);
Assert.Equal("A", list[0].ToString());
Assert.Equal("B", list[1].ToString());
Assert.Equal("C", list[2].ToString());
Assert.Equal("A B C ", list.ToFullString());
var elementA = list[0];
var elementB = list[1];
var elementC = list[2];
Assert.Equal(0, list.IndexOf(elementA));
Assert.Equal(1, list.IndexOf(elementB));
Assert.Equal(2, list.IndexOf(elementC));
var tokenD = SyntaxFactory.ParseToken("D ");
var tokenE = SyntaxFactory.ParseToken("E ");
var newList = list.Add(tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("D A B C ", newList.ToFullString());
newList = list.Insert(1, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A D B C ", newList.ToFullString());
newList = list.Insert(2, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B D C ", newList.ToFullString());
newList = list.Insert(3, tokenD);
Assert.Equal(4, newList.Count);
Assert.Equal("A B C D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("D E A B C ", newList.ToFullString());
newList = list.InsertRange(1, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A D E B C ", newList.ToFullString());
newList = list.InsertRange(2, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B D E C ", newList.ToFullString());
newList = list.InsertRange(3, new[] { tokenD, tokenE });
Assert.Equal(5, newList.Count);
Assert.Equal("A B C D E ", newList.ToFullString());
newList = list.RemoveAt(0);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.RemoveAt(list.Count - 1);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Remove(elementA);
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.Remove(elementB);
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.Remove(elementC);
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
newList = list.Replace(elementA, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("D B C ", newList.ToFullString());
newList = list.Replace(elementB, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A D C ", newList.ToFullString());
newList = list.Replace(elementC, tokenD);
Assert.Equal(3, newList.Count);
Assert.Equal("A B D ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new[] { tokenD, tokenE });
Assert.Equal(4, newList.Count);
Assert.Equal("D E B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new[] { tokenD, tokenE });
Assert.Equal(4, newList.Count);
Assert.Equal("A D E C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new[] { tokenD, tokenE });
Assert.Equal(4, newList.Count);
Assert.Equal("A B D E ", newList.ToFullString());
newList = list.ReplaceRange(elementA, new SyntaxToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("B C ", newList.ToFullString());
newList = list.ReplaceRange(elementB, new SyntaxToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A C ", newList.ToFullString());
newList = list.ReplaceRange(elementC, new SyntaxToken[] { });
Assert.Equal(2, newList.Count);
Assert.Equal("A B ", newList.ToFullString());
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null));
Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxToken>)null));
}
[Fact]
public void TestAddInsertRemoveReplaceOnEmptyList()
{
DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.TokenList());
DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxTokenList));
}
private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTokenList list)
{
Assert.Equal(0, list.Count);
var tokenD = SyntaxFactory.ParseToken("D ");
var tokenE = SyntaxFactory.ParseToken("E ");
var newList = list.Add(tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.AddRange(new[] { tokenD, tokenE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Insert(0, tokenD);
Assert.Equal(1, newList.Count);
Assert.Equal("D ", newList.ToFullString());
newList = list.InsertRange(0, new[] { tokenD, tokenE });
Assert.Equal(2, newList.Count);
Assert.Equal("D E ", newList.ToFullString());
newList = list.Remove(tokenD);
Assert.Equal(0, newList.Count);
Assert.Equal(-1, list.IndexOf(tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(tokenD, tokenE));
Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(tokenD, new[] { tokenE }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken)));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken)));
Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null));
Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null));
}
[Fact]
public void Extensions()
{
var list = SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.SizeOfKeyword),
SyntaxFactory.Literal("x"),
SyntaxFactory.Token(SyntaxKind.DotToken));
Assert.Equal(0, list.IndexOf(SyntaxKind.SizeOfKeyword));
Assert.True(list.Any(SyntaxKind.SizeOfKeyword));
Assert.Equal(1, list.IndexOf(SyntaxKind.StringLiteralToken));
Assert.True(list.Any(SyntaxKind.StringLiteralToken));
Assert.Equal(2, list.IndexOf(SyntaxKind.DotToken));
Assert.True(list.Any(SyntaxKind.DotToken));
Assert.Equal(-1, list.IndexOf(SyntaxKind.NullKeyword));
Assert.False(list.Any(SyntaxKind.NullKeyword));
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/CSharpSyntaxContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
internal sealed class CSharpSyntaxContext : SyntaxContext
{
public readonly TypeDeclarationSyntax? ContainingTypeDeclaration;
public readonly BaseTypeDeclarationSyntax? ContainingTypeOrEnumDeclaration;
public readonly bool IsInNonUserCode;
public readonly bool IsPreProcessorKeywordContext;
public readonly bool IsGlobalStatementContext;
public readonly bool IsNonAttributeExpressionContext;
public readonly bool IsConstantExpressionContext;
public readonly bool IsLabelContext;
public readonly bool IsTypeArgumentOfConstraintContext;
public readonly bool IsIsOrAsOrSwitchOrWithExpressionContext;
public readonly bool IsObjectCreationTypeContext;
public readonly bool IsDefiniteCastTypeContext;
public readonly bool IsGenericTypeArgumentContext;
public readonly bool IsEnumBaseListContext;
public readonly bool IsIsOrAsTypeContext;
public readonly bool IsLocalVariableDeclarationContext;
public readonly bool IsDeclarationExpressionContext;
public readonly bool IsFixedVariableDeclarationContext;
public readonly bool IsParameterTypeContext;
public readonly bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext;
public readonly bool IsImplicitOrExplicitOperatorTypeContext;
public readonly bool IsPrimaryFunctionExpressionContext;
public readonly bool IsDelegateReturnTypeContext;
public readonly bool IsTypeOfExpressionContext;
public readonly ISet<SyntaxKind> PrecedingModifiers;
public readonly bool IsInstanceContext;
public readonly bool IsCrefContext;
public readonly bool IsCatchFilterContext;
public readonly bool IsDestructorTypeContext;
public readonly bool IsLeftSideOfImportAliasDirective;
public readonly bool IsFunctionPointerTypeArgumentContext;
public readonly bool IsLocalFunctionDeclarationContext;
private CSharpSyntaxContext(
Workspace? workspace,
SemanticModel semanticModel,
int position,
SyntaxToken leftToken,
SyntaxToken targetToken,
TypeDeclarationSyntax? containingTypeDeclaration,
BaseTypeDeclarationSyntax? containingTypeOrEnumDeclaration,
bool isInNonUserCode,
bool isPreProcessorDirectiveContext,
bool isPreProcessorKeywordContext,
bool isPreProcessorExpressionContext,
bool isTypeContext,
bool isNamespaceContext,
bool isNamespaceDeclarationNameContext,
bool isStatementContext,
bool isGlobalStatementContext,
bool isAnyExpressionContext,
bool isNonAttributeExpressionContext,
bool isConstantExpressionContext,
bool isAttributeNameContext,
bool isEnumTypeMemberAccessContext,
bool isNameOfContext,
bool isInQuery,
bool isInImportsDirective,
bool isLeftSideOfImportAliasDirective,
bool isLabelContext,
bool isTypeArgumentOfConstraintContext,
bool isRightOfDotOrArrowOrColonColon,
bool isIsOrAsOrSwitchOrWithExpressionContext,
bool isObjectCreationTypeContext,
bool isDefiniteCastTypeContext,
bool isGenericTypeArgumentContext,
bool isEnumBaseListContext,
bool isIsOrAsTypeContext,
bool isLocalVariableDeclarationContext,
bool isDeclarationExpressionContext,
bool isFixedVariableDeclarationContext,
bool isParameterTypeContext,
bool isPossibleLambdaOrAnonymousMethodParameterTypeContext,
bool isImplicitOrExplicitOperatorTypeContext,
bool isPrimaryFunctionExpressionContext,
bool isDelegateReturnTypeContext,
bool isTypeOfExpressionContext,
ISet<SyntaxKind> precedingModifiers,
bool isInstanceContext,
bool isCrefContext,
bool isCatchFilterContext,
bool isDestructorTypeContext,
bool isPossibleTupleContext,
bool isStartPatternContext,
bool isAfterPatternContext,
bool isRightSideOfNumericType,
bool isInArgumentList,
bool isFunctionPointerTypeArgumentContext,
bool isLocalFunctionDeclarationContext,
CancellationToken cancellationToken)
: base(workspace, semanticModel, position, leftToken, targetToken,
isTypeContext, isNamespaceContext, isNamespaceDeclarationNameContext,
isPreProcessorDirectiveContext, isPreProcessorExpressionContext,
isRightOfDotOrArrowOrColonColon, isStatementContext, isAnyExpressionContext,
isAttributeNameContext, isEnumTypeMemberAccessContext, isNameOfContext,
isInQuery, isInImportsDirective, IsWithinAsyncMethod(), isPossibleTupleContext,
isStartPatternContext, isAfterPatternContext, isRightSideOfNumericType, isInArgumentList,
cancellationToken)
{
this.ContainingTypeDeclaration = containingTypeDeclaration;
this.ContainingTypeOrEnumDeclaration = containingTypeOrEnumDeclaration;
this.IsInNonUserCode = isInNonUserCode;
this.IsPreProcessorKeywordContext = isPreProcessorKeywordContext;
this.IsGlobalStatementContext = isGlobalStatementContext;
this.IsNonAttributeExpressionContext = isNonAttributeExpressionContext;
this.IsConstantExpressionContext = isConstantExpressionContext;
this.IsLabelContext = isLabelContext;
this.IsTypeArgumentOfConstraintContext = isTypeArgumentOfConstraintContext;
this.IsIsOrAsOrSwitchOrWithExpressionContext = isIsOrAsOrSwitchOrWithExpressionContext;
this.IsObjectCreationTypeContext = isObjectCreationTypeContext;
this.IsDefiniteCastTypeContext = isDefiniteCastTypeContext;
this.IsGenericTypeArgumentContext = isGenericTypeArgumentContext;
this.IsEnumBaseListContext = isEnumBaseListContext;
this.IsIsOrAsTypeContext = isIsOrAsTypeContext;
this.IsLocalVariableDeclarationContext = isLocalVariableDeclarationContext;
this.IsDeclarationExpressionContext = isDeclarationExpressionContext;
this.IsFixedVariableDeclarationContext = isFixedVariableDeclarationContext;
this.IsParameterTypeContext = isParameterTypeContext;
this.IsPossibleLambdaOrAnonymousMethodParameterTypeContext = isPossibleLambdaOrAnonymousMethodParameterTypeContext;
this.IsImplicitOrExplicitOperatorTypeContext = isImplicitOrExplicitOperatorTypeContext;
this.IsPrimaryFunctionExpressionContext = isPrimaryFunctionExpressionContext;
this.IsDelegateReturnTypeContext = isDelegateReturnTypeContext;
this.IsTypeOfExpressionContext = isTypeOfExpressionContext;
this.PrecedingModifiers = precedingModifiers;
this.IsInstanceContext = isInstanceContext;
this.IsCrefContext = isCrefContext;
this.IsCatchFilterContext = isCatchFilterContext;
this.IsDestructorTypeContext = isDestructorTypeContext;
this.IsLeftSideOfImportAliasDirective = isLeftSideOfImportAliasDirective;
this.IsFunctionPointerTypeArgumentContext = isFunctionPointerTypeArgumentContext;
this.IsLocalFunctionDeclarationContext = isLocalFunctionDeclarationContext;
}
public static CSharpSyntaxContext CreateContext(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> CreateContextWorker(workspace, semanticModel, position, cancellationToken);
private static CSharpSyntaxContext CreateContextWorker(Workspace? workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
var syntaxTree = semanticModel.SyntaxTree;
var isInNonUserCode = syntaxTree.IsInNonUserCode(position, cancellationToken);
var preProcessorTokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true);
var isPreProcessorDirectiveContext = syntaxTree.IsPreProcessorDirectiveContext(position, preProcessorTokenOnLeftOfPosition, cancellationToken);
var leftToken = isPreProcessorDirectiveContext
? preProcessorTokenOnLeftOfPosition
: syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position);
var isPreProcessorKeywordContext = isPreProcessorDirectiveContext
? syntaxTree.IsPreProcessorKeywordContext(position, leftToken)
: false;
var isPreProcessorExpressionContext = isPreProcessorDirectiveContext
? targetToken.IsPreProcessorExpressionContext()
: false;
var isStatementContext = !isPreProcessorDirectiveContext
? targetToken.IsBeginningOfStatementContext()
: false;
var isGlobalStatementContext = !isPreProcessorDirectiveContext
? syntaxTree.IsGlobalStatementContext(position, cancellationToken)
: false;
var isAnyExpressionContext = !isPreProcessorDirectiveContext
? syntaxTree.IsExpressionContext(position, leftToken, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel)
: false;
var isNonAttributeExpressionContext = !isPreProcessorDirectiveContext
? syntaxTree.IsExpressionContext(position, leftToken, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModel)
: false;
var isConstantExpressionContext = !isPreProcessorDirectiveContext
? syntaxTree.IsConstantExpressionContext(position, leftToken)
: false;
var containingTypeDeclaration = syntaxTree.GetContainingTypeDeclaration(position, cancellationToken);
var containingTypeOrEnumDeclaration = syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken);
var isDestructorTypeContext = targetToken.IsKind(SyntaxKind.TildeToken) &&
targetToken.Parent.IsKind(SyntaxKind.DestructorDeclaration) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration);
// Typing a dot after a numeric expression (numericExpression.)
// - maybe a start of MemberAccessExpression like numericExpression.Member.
// - or it maybe a start of a range expression like numericExpression..anotherNumericExpression (starting C# 8.0)
// Therefore, in the scenario, we want the completion to be __soft selected__ until user types the next character after the dot.
// If the second dot was typed, we just insert two dots.
var isRightSideOfNumericType = leftToken.IsNumericTypeContext(semanticModel, cancellationToken);
var isArgumentListToken = targetToken.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.AttributeArgumentList, SyntaxKind.ArrayRankSpecifier);
var isLocalFunctionDeclarationContext = syntaxTree.IsLocalFunctionDeclarationContext(position, cancellationToken);
return new CSharpSyntaxContext(
workspace: workspace,
semanticModel: semanticModel,
position: position,
leftToken: leftToken,
targetToken: targetToken,
containingTypeDeclaration: containingTypeDeclaration,
containingTypeOrEnumDeclaration: containingTypeOrEnumDeclaration,
isInNonUserCode: isInNonUserCode,
isPreProcessorDirectiveContext: isPreProcessorDirectiveContext,
isPreProcessorKeywordContext: isPreProcessorKeywordContext,
isPreProcessorExpressionContext: isPreProcessorExpressionContext,
isTypeContext: syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt: semanticModel),
isNamespaceContext: syntaxTree.IsNamespaceContext(position, cancellationToken, semanticModelOpt: semanticModel),
isNamespaceDeclarationNameContext: syntaxTree.IsNamespaceDeclarationNameContext(position, cancellationToken),
isStatementContext: isStatementContext,
isGlobalStatementContext: isGlobalStatementContext,
isAnyExpressionContext: isAnyExpressionContext,
isNonAttributeExpressionContext: isNonAttributeExpressionContext,
isConstantExpressionContext: isConstantExpressionContext,
isAttributeNameContext: syntaxTree.IsAttributeNameContext(position, cancellationToken),
isEnumTypeMemberAccessContext: syntaxTree.IsEnumTypeMemberAccessContext(semanticModel, position, cancellationToken),
isNameOfContext: syntaxTree.IsNameOfContext(position, semanticModel, cancellationToken),
isInQuery: leftToken.GetAncestor<QueryExpressionSyntax>() != null,
isInImportsDirective: leftToken.GetAncestor<UsingDirectiveSyntax>() != null,
isLeftSideOfImportAliasDirective: IsLeftSideOfUsingAliasDirective(leftToken),
isLabelContext: syntaxTree.IsLabelContext(position, cancellationToken),
isTypeArgumentOfConstraintContext: syntaxTree.IsTypeArgumentOfConstraintClause(position, cancellationToken),
isRightOfDotOrArrowOrColonColon: syntaxTree.IsRightOfDotOrArrowOrColonColon(position, targetToken, cancellationToken),
isIsOrAsOrSwitchOrWithExpressionContext: syntaxTree.IsIsOrAsOrSwitchOrWithExpressionContext(semanticModel, position, leftToken, cancellationToken),
isObjectCreationTypeContext: syntaxTree.IsObjectCreationTypeContext(position, leftToken, cancellationToken),
isDefiniteCastTypeContext: syntaxTree.IsDefiniteCastTypeContext(position, leftToken),
isGenericTypeArgumentContext: syntaxTree.IsGenericTypeArgumentContext(position, leftToken, cancellationToken),
isEnumBaseListContext: syntaxTree.IsEnumBaseListContext(position, leftToken),
isIsOrAsTypeContext: syntaxTree.IsIsOrAsTypeContext(position, leftToken),
isLocalVariableDeclarationContext: syntaxTree.IsLocalVariableDeclarationContext(position, leftToken, cancellationToken),
isDeclarationExpressionContext: syntaxTree.IsDeclarationExpressionContext(position, leftToken),
isFixedVariableDeclarationContext: syntaxTree.IsFixedVariableDeclarationContext(position, leftToken),
isParameterTypeContext: syntaxTree.IsParameterTypeContext(position, leftToken),
isPossibleLambdaOrAnonymousMethodParameterTypeContext: syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, leftToken, cancellationToken),
isImplicitOrExplicitOperatorTypeContext: syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, leftToken),
isPrimaryFunctionExpressionContext: syntaxTree.IsPrimaryFunctionExpressionContext(position, leftToken),
isDelegateReturnTypeContext: syntaxTree.IsDelegateReturnTypeContext(position, leftToken),
isTypeOfExpressionContext: syntaxTree.IsTypeOfExpressionContext(position, leftToken),
precedingModifiers: syntaxTree.GetPrecedingModifiers(position, leftToken),
isInstanceContext: syntaxTree.IsInstanceContext(targetToken, semanticModel, cancellationToken),
isCrefContext: syntaxTree.IsCrefContext(position, cancellationToken) && !leftToken.IsKind(SyntaxKind.DotToken),
isCatchFilterContext: syntaxTree.IsCatchFilterContext(position, leftToken),
isDestructorTypeContext: isDestructorTypeContext,
isPossibleTupleContext: syntaxTree.IsPossibleTupleContext(leftToken, position),
isStartPatternContext: syntaxTree.IsAtStartOfPattern(leftToken, position),
isAfterPatternContext: syntaxTree.IsAtEndOfPattern(leftToken, position),
isRightSideOfNumericType: isRightSideOfNumericType,
isInArgumentList: isArgumentListToken,
isFunctionPointerTypeArgumentContext: syntaxTree.IsFunctionPointerTypeArgumentContext(position, leftToken, cancellationToken),
isLocalFunctionDeclarationContext: isLocalFunctionDeclarationContext,
cancellationToken: cancellationToken);
}
public static CSharpSyntaxContext CreateContext_Test(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
var inferenceService = new CSharpTypeInferenceService();
_ = inferenceService.InferTypes(semanticModel, position, cancellationToken);
return CreateContextWorker(workspace: null, semanticModel: semanticModel, position: position, cancellationToken: cancellationToken);
}
private static new bool IsWithinAsyncMethod()
{
// TODO: Implement this if any C# completion code needs to know if it is in an async
// method or not.
return false;
}
public bool IsTypeAttributeContext(CancellationToken cancellationToken)
{
// cases:
// [ |
// class C { [ |
var token = this.TargetToken;
// Note that we pass the token.SpanStart to IsTypeDeclarationContext below. This is a bit subtle,
// but we want to be sure that the attribute itself (i.e. the open square bracket, '[') is in a
// type declaration context.
if (token.Kind() == SyntaxKind.OpenBracketToken &&
token.Parent.IsKind(SyntaxKind.AttributeList) &&
this.SyntaxTree.IsTypeDeclarationContext(
token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
{
return true;
}
return false;
}
public bool IsTypeDeclarationContext(
ISet<SyntaxKind>? validModifiers = null,
ISet<SyntaxKind>? validTypeDeclarations = null,
bool canBePartial = false,
CancellationToken cancellationToken = default)
{
return this.SyntaxTree.IsTypeDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken);
}
public bool IsMemberAttributeContext(ISet<SyntaxKind> validTypeDeclarations, CancellationToken cancellationToken)
{
// cases:
// class C { [ |
var token = this.TargetToken;
if (token.Kind() == SyntaxKind.OpenBracketToken &&
token.Parent.IsKind(SyntaxKind.AttributeList))
{
if (token.Parent.Parent is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } })
{
return true;
}
if (SyntaxTree.IsMemberDeclarationContext(
token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: validTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
{
return true;
}
}
return false;
}
public bool IsStatementAttributeContext()
{
var token = TargetToken;
if (token.Kind() == SyntaxKind.OpenBracketToken &&
token.Parent.IsKind(SyntaxKind.AttributeList) &&
token.Parent.Parent is StatementSyntax)
{
return true;
}
return false;
}
public bool IsMemberDeclarationContext(
ISet<SyntaxKind>? validModifiers = null,
ISet<SyntaxKind>? validTypeDeclarations = null,
bool canBePartial = false,
CancellationToken cancellationToken = default)
{
return this.SyntaxTree.IsMemberDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken);
}
private static bool IsLeftSideOfUsingAliasDirective(SyntaxToken leftToken)
{
var usingDirective = leftToken.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null)
{
// No = token:
if (usingDirective.Alias == null || usingDirective.Alias.EqualsToken.IsMissing)
{
return true;
}
return leftToken.SpanStart < usingDirective.Alias.EqualsToken.SpanStart;
}
return false;
}
internal override ITypeInferenceService GetTypeInferenceServiceWithoutWorkspace()
=> new CSharpTypeInferenceService();
/// <summary>
/// Is this a possible position for an await statement (`await using` or `await foreach`)?
/// </summary>
internal bool IsAwaitStatementContext(int position, CancellationToken cancellationToken)
{
var leftToken = this.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position);
if (targetToken.IsKind(SyntaxKind.AwaitKeyword))
{
var previousToken = targetToken.GetPreviousToken();
if (previousToken.IsBeginningOfStatementContext())
{
return true;
}
return SyntaxTree.IsGlobalStatementContext(targetToken.SpanStart, cancellationToken);
}
else if (SyntaxTree.IsScript()
&& targetToken.IsKind(SyntaxKind.IdentifierToken)
&& targetToken.HasMatchingText(SyntaxKind.AwaitKeyword))
{
// The 'await' keyword is parsed as an identifier in C# script
return SyntaxTree.IsGlobalStatementContext(targetToken.SpanStart, cancellationToken);
}
return false;
}
/// <summary>
/// Determines whether await should be suggested in a given position.
/// </summary>
internal override bool IsAwaitKeywordContext()
{
if (IsGlobalStatementContext)
{
return true;
}
if (IsAnyExpressionContext || IsStatementContext)
{
foreach (var node in LeftToken.GetAncestors<SyntaxNode>())
{
if (node.IsAnyLambdaOrAnonymousMethod())
{
return true;
}
if (node.IsKind(SyntaxKind.QueryExpression))
{
return false;
}
if (node.IsKind(SyntaxKind.LockStatement, out LockStatementSyntax? lockStatement))
{
if (lockStatement.Statement != null &&
!lockStatement.Statement.IsMissing &&
lockStatement.Statement.Span.Contains(Position))
{
return false;
}
}
}
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.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
internal sealed class CSharpSyntaxContext : SyntaxContext
{
public readonly TypeDeclarationSyntax? ContainingTypeDeclaration;
public readonly BaseTypeDeclarationSyntax? ContainingTypeOrEnumDeclaration;
public readonly bool IsInNonUserCode;
public readonly bool IsPreProcessorKeywordContext;
public readonly bool IsGlobalStatementContext;
public readonly bool IsNonAttributeExpressionContext;
public readonly bool IsConstantExpressionContext;
public readonly bool IsLabelContext;
public readonly bool IsTypeArgumentOfConstraintContext;
public readonly bool IsIsOrAsOrSwitchOrWithExpressionContext;
public readonly bool IsObjectCreationTypeContext;
public readonly bool IsDefiniteCastTypeContext;
public readonly bool IsGenericTypeArgumentContext;
public readonly bool IsEnumBaseListContext;
public readonly bool IsIsOrAsTypeContext;
public readonly bool IsLocalVariableDeclarationContext;
public readonly bool IsDeclarationExpressionContext;
public readonly bool IsFixedVariableDeclarationContext;
public readonly bool IsParameterTypeContext;
public readonly bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext;
public readonly bool IsImplicitOrExplicitOperatorTypeContext;
public readonly bool IsPrimaryFunctionExpressionContext;
public readonly bool IsDelegateReturnTypeContext;
public readonly bool IsTypeOfExpressionContext;
public readonly ISet<SyntaxKind> PrecedingModifiers;
public readonly bool IsInstanceContext;
public readonly bool IsCrefContext;
public readonly bool IsCatchFilterContext;
public readonly bool IsDestructorTypeContext;
public readonly bool IsLeftSideOfImportAliasDirective;
public readonly bool IsFunctionPointerTypeArgumentContext;
public readonly bool IsLocalFunctionDeclarationContext;
private CSharpSyntaxContext(
Workspace? workspace,
SemanticModel semanticModel,
int position,
SyntaxToken leftToken,
SyntaxToken targetToken,
TypeDeclarationSyntax? containingTypeDeclaration,
BaseTypeDeclarationSyntax? containingTypeOrEnumDeclaration,
bool isInNonUserCode,
bool isPreProcessorDirectiveContext,
bool isPreProcessorKeywordContext,
bool isPreProcessorExpressionContext,
bool isTypeContext,
bool isNamespaceContext,
bool isNamespaceDeclarationNameContext,
bool isStatementContext,
bool isGlobalStatementContext,
bool isAnyExpressionContext,
bool isNonAttributeExpressionContext,
bool isConstantExpressionContext,
bool isAttributeNameContext,
bool isEnumTypeMemberAccessContext,
bool isNameOfContext,
bool isInQuery,
bool isInImportsDirective,
bool isLeftSideOfImportAliasDirective,
bool isLabelContext,
bool isTypeArgumentOfConstraintContext,
bool isRightOfDotOrArrowOrColonColon,
bool isIsOrAsOrSwitchOrWithExpressionContext,
bool isObjectCreationTypeContext,
bool isDefiniteCastTypeContext,
bool isGenericTypeArgumentContext,
bool isEnumBaseListContext,
bool isIsOrAsTypeContext,
bool isLocalVariableDeclarationContext,
bool isDeclarationExpressionContext,
bool isFixedVariableDeclarationContext,
bool isParameterTypeContext,
bool isPossibleLambdaOrAnonymousMethodParameterTypeContext,
bool isImplicitOrExplicitOperatorTypeContext,
bool isPrimaryFunctionExpressionContext,
bool isDelegateReturnTypeContext,
bool isTypeOfExpressionContext,
ISet<SyntaxKind> precedingModifiers,
bool isInstanceContext,
bool isCrefContext,
bool isCatchFilterContext,
bool isDestructorTypeContext,
bool isPossibleTupleContext,
bool isStartPatternContext,
bool isAfterPatternContext,
bool isRightSideOfNumericType,
bool isInArgumentList,
bool isFunctionPointerTypeArgumentContext,
bool isLocalFunctionDeclarationContext,
CancellationToken cancellationToken)
: base(workspace, semanticModel, position, leftToken, targetToken,
isTypeContext, isNamespaceContext, isNamespaceDeclarationNameContext,
isPreProcessorDirectiveContext, isPreProcessorExpressionContext,
isRightOfDotOrArrowOrColonColon, isStatementContext, isAnyExpressionContext,
isAttributeNameContext, isEnumTypeMemberAccessContext, isNameOfContext,
isInQuery, isInImportsDirective, IsWithinAsyncMethod(), isPossibleTupleContext,
isStartPatternContext, isAfterPatternContext, isRightSideOfNumericType, isInArgumentList,
cancellationToken)
{
this.ContainingTypeDeclaration = containingTypeDeclaration;
this.ContainingTypeOrEnumDeclaration = containingTypeOrEnumDeclaration;
this.IsInNonUserCode = isInNonUserCode;
this.IsPreProcessorKeywordContext = isPreProcessorKeywordContext;
this.IsGlobalStatementContext = isGlobalStatementContext;
this.IsNonAttributeExpressionContext = isNonAttributeExpressionContext;
this.IsConstantExpressionContext = isConstantExpressionContext;
this.IsLabelContext = isLabelContext;
this.IsTypeArgumentOfConstraintContext = isTypeArgumentOfConstraintContext;
this.IsIsOrAsOrSwitchOrWithExpressionContext = isIsOrAsOrSwitchOrWithExpressionContext;
this.IsObjectCreationTypeContext = isObjectCreationTypeContext;
this.IsDefiniteCastTypeContext = isDefiniteCastTypeContext;
this.IsGenericTypeArgumentContext = isGenericTypeArgumentContext;
this.IsEnumBaseListContext = isEnumBaseListContext;
this.IsIsOrAsTypeContext = isIsOrAsTypeContext;
this.IsLocalVariableDeclarationContext = isLocalVariableDeclarationContext;
this.IsDeclarationExpressionContext = isDeclarationExpressionContext;
this.IsFixedVariableDeclarationContext = isFixedVariableDeclarationContext;
this.IsParameterTypeContext = isParameterTypeContext;
this.IsPossibleLambdaOrAnonymousMethodParameterTypeContext = isPossibleLambdaOrAnonymousMethodParameterTypeContext;
this.IsImplicitOrExplicitOperatorTypeContext = isImplicitOrExplicitOperatorTypeContext;
this.IsPrimaryFunctionExpressionContext = isPrimaryFunctionExpressionContext;
this.IsDelegateReturnTypeContext = isDelegateReturnTypeContext;
this.IsTypeOfExpressionContext = isTypeOfExpressionContext;
this.PrecedingModifiers = precedingModifiers;
this.IsInstanceContext = isInstanceContext;
this.IsCrefContext = isCrefContext;
this.IsCatchFilterContext = isCatchFilterContext;
this.IsDestructorTypeContext = isDestructorTypeContext;
this.IsLeftSideOfImportAliasDirective = isLeftSideOfImportAliasDirective;
this.IsFunctionPointerTypeArgumentContext = isFunctionPointerTypeArgumentContext;
this.IsLocalFunctionDeclarationContext = isLocalFunctionDeclarationContext;
}
public static CSharpSyntaxContext CreateContext(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> CreateContextWorker(workspace, semanticModel, position, cancellationToken);
private static CSharpSyntaxContext CreateContextWorker(Workspace? workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
var syntaxTree = semanticModel.SyntaxTree;
var isInNonUserCode = syntaxTree.IsInNonUserCode(position, cancellationToken);
var preProcessorTokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true);
var isPreProcessorDirectiveContext = syntaxTree.IsPreProcessorDirectiveContext(position, preProcessorTokenOnLeftOfPosition, cancellationToken);
var leftToken = isPreProcessorDirectiveContext
? preProcessorTokenOnLeftOfPosition
: syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position);
var isPreProcessorKeywordContext = isPreProcessorDirectiveContext
? syntaxTree.IsPreProcessorKeywordContext(position, leftToken)
: false;
var isPreProcessorExpressionContext = isPreProcessorDirectiveContext
? targetToken.IsPreProcessorExpressionContext()
: false;
var isStatementContext = !isPreProcessorDirectiveContext
? targetToken.IsBeginningOfStatementContext()
: false;
var isGlobalStatementContext = !isPreProcessorDirectiveContext
? syntaxTree.IsGlobalStatementContext(position, cancellationToken)
: false;
var isAnyExpressionContext = !isPreProcessorDirectiveContext
? syntaxTree.IsExpressionContext(position, leftToken, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel)
: false;
var isNonAttributeExpressionContext = !isPreProcessorDirectiveContext
? syntaxTree.IsExpressionContext(position, leftToken, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModel)
: false;
var isConstantExpressionContext = !isPreProcessorDirectiveContext
? syntaxTree.IsConstantExpressionContext(position, leftToken)
: false;
var containingTypeDeclaration = syntaxTree.GetContainingTypeDeclaration(position, cancellationToken);
var containingTypeOrEnumDeclaration = syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken);
var isDestructorTypeContext = targetToken.IsKind(SyntaxKind.TildeToken) &&
targetToken.Parent.IsKind(SyntaxKind.DestructorDeclaration) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration);
// Typing a dot after a numeric expression (numericExpression.)
// - maybe a start of MemberAccessExpression like numericExpression.Member.
// - or it maybe a start of a range expression like numericExpression..anotherNumericExpression (starting C# 8.0)
// Therefore, in the scenario, we want the completion to be __soft selected__ until user types the next character after the dot.
// If the second dot was typed, we just insert two dots.
var isRightSideOfNumericType = leftToken.IsNumericTypeContext(semanticModel, cancellationToken);
var isArgumentListToken = targetToken.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.AttributeArgumentList, SyntaxKind.ArrayRankSpecifier);
var isLocalFunctionDeclarationContext = syntaxTree.IsLocalFunctionDeclarationContext(position, cancellationToken);
return new CSharpSyntaxContext(
workspace: workspace,
semanticModel: semanticModel,
position: position,
leftToken: leftToken,
targetToken: targetToken,
containingTypeDeclaration: containingTypeDeclaration,
containingTypeOrEnumDeclaration: containingTypeOrEnumDeclaration,
isInNonUserCode: isInNonUserCode,
isPreProcessorDirectiveContext: isPreProcessorDirectiveContext,
isPreProcessorKeywordContext: isPreProcessorKeywordContext,
isPreProcessorExpressionContext: isPreProcessorExpressionContext,
isTypeContext: syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt: semanticModel),
isNamespaceContext: syntaxTree.IsNamespaceContext(position, cancellationToken, semanticModelOpt: semanticModel),
isNamespaceDeclarationNameContext: syntaxTree.IsNamespaceDeclarationNameContext(position, cancellationToken),
isStatementContext: isStatementContext,
isGlobalStatementContext: isGlobalStatementContext,
isAnyExpressionContext: isAnyExpressionContext,
isNonAttributeExpressionContext: isNonAttributeExpressionContext,
isConstantExpressionContext: isConstantExpressionContext,
isAttributeNameContext: syntaxTree.IsAttributeNameContext(position, cancellationToken),
isEnumTypeMemberAccessContext: syntaxTree.IsEnumTypeMemberAccessContext(semanticModel, position, cancellationToken),
isNameOfContext: syntaxTree.IsNameOfContext(position, semanticModel, cancellationToken),
isInQuery: leftToken.GetAncestor<QueryExpressionSyntax>() != null,
isInImportsDirective: leftToken.GetAncestor<UsingDirectiveSyntax>() != null,
isLeftSideOfImportAliasDirective: IsLeftSideOfUsingAliasDirective(leftToken),
isLabelContext: syntaxTree.IsLabelContext(position, cancellationToken),
isTypeArgumentOfConstraintContext: syntaxTree.IsTypeArgumentOfConstraintClause(position, cancellationToken),
isRightOfDotOrArrowOrColonColon: syntaxTree.IsRightOfDotOrArrowOrColonColon(position, targetToken, cancellationToken),
isIsOrAsOrSwitchOrWithExpressionContext: syntaxTree.IsIsOrAsOrSwitchOrWithExpressionContext(semanticModel, position, leftToken, cancellationToken),
isObjectCreationTypeContext: syntaxTree.IsObjectCreationTypeContext(position, leftToken, cancellationToken),
isDefiniteCastTypeContext: syntaxTree.IsDefiniteCastTypeContext(position, leftToken),
isGenericTypeArgumentContext: syntaxTree.IsGenericTypeArgumentContext(position, leftToken, cancellationToken),
isEnumBaseListContext: syntaxTree.IsEnumBaseListContext(position, leftToken),
isIsOrAsTypeContext: syntaxTree.IsIsOrAsTypeContext(position, leftToken),
isLocalVariableDeclarationContext: syntaxTree.IsLocalVariableDeclarationContext(position, leftToken, cancellationToken),
isDeclarationExpressionContext: syntaxTree.IsDeclarationExpressionContext(position, leftToken),
isFixedVariableDeclarationContext: syntaxTree.IsFixedVariableDeclarationContext(position, leftToken),
isParameterTypeContext: syntaxTree.IsParameterTypeContext(position, leftToken),
isPossibleLambdaOrAnonymousMethodParameterTypeContext: syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, leftToken, cancellationToken),
isImplicitOrExplicitOperatorTypeContext: syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, leftToken),
isPrimaryFunctionExpressionContext: syntaxTree.IsPrimaryFunctionExpressionContext(position, leftToken),
isDelegateReturnTypeContext: syntaxTree.IsDelegateReturnTypeContext(position, leftToken),
isTypeOfExpressionContext: syntaxTree.IsTypeOfExpressionContext(position, leftToken),
precedingModifiers: syntaxTree.GetPrecedingModifiers(position, leftToken),
isInstanceContext: syntaxTree.IsInstanceContext(targetToken, semanticModel, cancellationToken),
isCrefContext: syntaxTree.IsCrefContext(position, cancellationToken) && !leftToken.IsKind(SyntaxKind.DotToken),
isCatchFilterContext: syntaxTree.IsCatchFilterContext(position, leftToken),
isDestructorTypeContext: isDestructorTypeContext,
isPossibleTupleContext: syntaxTree.IsPossibleTupleContext(leftToken, position),
isStartPatternContext: syntaxTree.IsAtStartOfPattern(leftToken, position),
isAfterPatternContext: syntaxTree.IsAtEndOfPattern(leftToken, position),
isRightSideOfNumericType: isRightSideOfNumericType,
isInArgumentList: isArgumentListToken,
isFunctionPointerTypeArgumentContext: syntaxTree.IsFunctionPointerTypeArgumentContext(position, leftToken, cancellationToken),
isLocalFunctionDeclarationContext: isLocalFunctionDeclarationContext,
cancellationToken: cancellationToken);
}
public static CSharpSyntaxContext CreateContext_Test(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
var inferenceService = new CSharpTypeInferenceService();
_ = inferenceService.InferTypes(semanticModel, position, cancellationToken);
return CreateContextWorker(workspace: null, semanticModel: semanticModel, position: position, cancellationToken: cancellationToken);
}
private static new bool IsWithinAsyncMethod()
{
// TODO: Implement this if any C# completion code needs to know if it is in an async
// method or not.
return false;
}
public bool IsTypeAttributeContext(CancellationToken cancellationToken)
{
// cases:
// [ |
// class C { [ |
var token = this.TargetToken;
// Note that we pass the token.SpanStart to IsTypeDeclarationContext below. This is a bit subtle,
// but we want to be sure that the attribute itself (i.e. the open square bracket, '[') is in a
// type declaration context.
if (token.Kind() == SyntaxKind.OpenBracketToken &&
token.Parent.IsKind(SyntaxKind.AttributeList) &&
this.SyntaxTree.IsTypeDeclarationContext(
token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
{
return true;
}
return false;
}
public bool IsTypeDeclarationContext(
ISet<SyntaxKind>? validModifiers = null,
ISet<SyntaxKind>? validTypeDeclarations = null,
bool canBePartial = false,
CancellationToken cancellationToken = default)
{
return this.SyntaxTree.IsTypeDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken);
}
public bool IsMemberAttributeContext(ISet<SyntaxKind> validTypeDeclarations, CancellationToken cancellationToken)
{
// cases:
// class C { [ |
var token = this.TargetToken;
if (token.Kind() == SyntaxKind.OpenBracketToken &&
token.Parent.IsKind(SyntaxKind.AttributeList))
{
if (token.Parent.Parent is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } })
{
return true;
}
if (SyntaxTree.IsMemberDeclarationContext(
token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: validTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken))
{
return true;
}
}
return false;
}
public bool IsStatementAttributeContext()
{
var token = TargetToken;
if (token.Kind() == SyntaxKind.OpenBracketToken &&
token.Parent.IsKind(SyntaxKind.AttributeList) &&
token.Parent.Parent is StatementSyntax)
{
return true;
}
return false;
}
public bool IsMemberDeclarationContext(
ISet<SyntaxKind>? validModifiers = null,
ISet<SyntaxKind>? validTypeDeclarations = null,
bool canBePartial = false,
CancellationToken cancellationToken = default)
{
return this.SyntaxTree.IsMemberDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken);
}
private static bool IsLeftSideOfUsingAliasDirective(SyntaxToken leftToken)
{
var usingDirective = leftToken.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null)
{
// No = token:
if (usingDirective.Alias == null || usingDirective.Alias.EqualsToken.IsMissing)
{
return true;
}
return leftToken.SpanStart < usingDirective.Alias.EqualsToken.SpanStart;
}
return false;
}
internal override ITypeInferenceService GetTypeInferenceServiceWithoutWorkspace()
=> new CSharpTypeInferenceService();
/// <summary>
/// Is this a possible position for an await statement (`await using` or `await foreach`)?
/// </summary>
internal bool IsAwaitStatementContext(int position, CancellationToken cancellationToken)
{
var leftToken = this.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position);
if (targetToken.IsKind(SyntaxKind.AwaitKeyword))
{
var previousToken = targetToken.GetPreviousToken();
if (previousToken.IsBeginningOfStatementContext())
{
return true;
}
return SyntaxTree.IsGlobalStatementContext(targetToken.SpanStart, cancellationToken);
}
else if (SyntaxTree.IsScript()
&& targetToken.IsKind(SyntaxKind.IdentifierToken)
&& targetToken.HasMatchingText(SyntaxKind.AwaitKeyword))
{
// The 'await' keyword is parsed as an identifier in C# script
return SyntaxTree.IsGlobalStatementContext(targetToken.SpanStart, cancellationToken);
}
return false;
}
/// <summary>
/// Determines whether await should be suggested in a given position.
/// </summary>
internal override bool IsAwaitKeywordContext()
{
if (IsGlobalStatementContext)
{
return true;
}
if (IsAnyExpressionContext || IsStatementContext)
{
foreach (var node in LeftToken.GetAncestors<SyntaxNode>())
{
if (node.IsAnyLambdaOrAnonymousMethod())
{
return true;
}
if (node.IsKind(SyntaxKind.QueryExpression))
{
return false;
}
if (node.IsKind(SyntaxKind.LockStatement, out LockStatementSyntax? lockStatement))
{
if (lockStatement.Statement != null &&
!lockStatement.Statement.IsMissing &&
lockStatement.Statement.Span.Contains(Position))
{
return false;
}
}
}
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,979 | Fix navigation in findrefs | Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | CyrusNajmabadi | "2021-08-27T22:47:12Z" | "2021-08-28T02:28:36Z" | 53ba85783fa120bf13cc95ab765369639540d9af | 2ab5dcb6f1e3e11e7cb9147ea2f88f6fa418fbf2 | Fix navigation in findrefs. Note: we need integration tests here. Filed https://github.com/dotnet/roslyn/issues/55978 to track this. | ./src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Progression;
namespace Microsoft.VisualStudio.LanguageServices.Progression
{
/// <summary>
/// A helper class that implements the creation of <see cref="GraphNode"/>s.
/// </summary>
public static class GraphNodeCreation
{
public static async Task<GraphNodeId> CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
switch (symbol.Kind)
{
case SymbolKind.Assembly:
return await GraphNodeIdCreation.GetIdForAssemblyAsync((IAssemblySymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Namespace:
return await GraphNodeIdCreation.GetIdForNamespaceAsync((INamespaceSymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.NamedType:
return await GraphNodeIdCreation.GetIdForTypeAsync((ITypeSymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Method:
case SymbolKind.Field:
case SymbolKind.Property:
case SymbolKind.Event:
return await GraphNodeIdCreation.GetIdForMemberAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Parameter:
return await GraphNodeIdCreation.GetIdForParameterAsync((IParameterSymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Local:
case SymbolKind.RangeVariable:
return await GraphNodeIdCreation.GetIdForLocalVariableAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
default:
throw new ArgumentException(string.Format(ServicesVSResources.Can_t_create_a_node_id_for_this_symbol_kind_colon_0, symbol));
}
}
public static async Task<GraphNode> CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (graph == null)
{
throw new ArgumentNullException(nameof(graph));
}
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
return await GraphBuilder.GetOrCreateNodeAsync(graph, symbol, solution, cancellationToken).ConfigureAwait(false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Progression;
namespace Microsoft.VisualStudio.LanguageServices.Progression
{
/// <summary>
/// A helper class that implements the creation of <see cref="GraphNode"/>s.
/// </summary>
public static class GraphNodeCreation
{
public static async Task<GraphNodeId> CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
switch (symbol.Kind)
{
case SymbolKind.Assembly:
return await GraphNodeIdCreation.GetIdForAssemblyAsync((IAssemblySymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Namespace:
return await GraphNodeIdCreation.GetIdForNamespaceAsync((INamespaceSymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.NamedType:
return await GraphNodeIdCreation.GetIdForTypeAsync((ITypeSymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Method:
case SymbolKind.Field:
case SymbolKind.Property:
case SymbolKind.Event:
return await GraphNodeIdCreation.GetIdForMemberAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Parameter:
return await GraphNodeIdCreation.GetIdForParameterAsync((IParameterSymbol)symbol, solution, cancellationToken).ConfigureAwait(false);
case SymbolKind.Local:
case SymbolKind.RangeVariable:
return await GraphNodeIdCreation.GetIdForLocalVariableAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
default:
throw new ArgumentException(string.Format(ServicesVSResources.Can_t_create_a_node_id_for_this_symbol_kind_colon_0, symbol));
}
}
public static async Task<GraphNode> CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (graph == null)
{
throw new ArgumentNullException(nameof(graph));
}
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
return await GraphBuilder.GetOrCreateNodeAsync(graph, symbol, solution, cancellationToken).ConfigureAwait(false);
}
}
}
| -1 |
dotnet/roslyn | 55,976 | [LSP] Semantic tokens: Utilize frozen partial compilations | Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | allisonchou | "2021-08-27T22:11:19Z" | "2021-08-31T21:08:24Z" | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | 1dd98de8b262e5dfe03edbba9858f242da32cadb | [LSP] Semantic tokens: Utilize frozen partial compilations. Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | ./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensEditsHandler.cs | // Licensed to the .NET Foundation under one or more 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
/// <summary>
/// Computes the semantic tokens edits for a file. An edit request is received every 500ms,
/// or every time an edit is made by the user.
/// </summary>
internal class SemanticTokensEditsHandler : IRequestHandler<LSP.SemanticTokensDeltaParams, SumType<LSP.SemanticTokens, LSP.SemanticTokensDelta>>
{
private readonly SemanticTokensCache _tokensCache;
public string Method => LSP.Methods.TextDocumentSemanticTokensFullDeltaName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public SemanticTokensEditsHandler(SemanticTokensCache tokensCache)
{
_tokensCache = tokensCache;
}
public TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensDeltaParams request)
{
Contract.ThrowIfNull(request.TextDocument);
return request.TextDocument;
}
public async Task<SumType<LSP.SemanticTokens, LSP.SemanticTokensDelta>> HandleRequestAsync(
LSP.SemanticTokensDeltaParams request,
RequestContext context,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.TextDocument, "TextDocument is null.");
Contract.ThrowIfNull(request.PreviousResultId, "previousResultId is null.");
Contract.ThrowIfNull(context.Document, "Document is null.");
// Even though we want to ultimately pass edits back to LSP, we still need to compute all semantic tokens,
// both for caching purposes and in order to have a baseline comparison when computing the edits.
var newSemanticTokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync(
context.Document, SemanticTokensCache.TokenTypeToIndex,
range: null, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(newSemanticTokensData, "newSemanticTokensData is null.");
// Getting the cached tokens for the document. If we don't have an applicable cached token set,
// we can't calculate edits, so we must return all semantic tokens instead.
var oldSemanticTokensData = await _tokensCache.GetCachedTokensDataAsync(
request.TextDocument.Uri, request.PreviousResultId, cancellationToken).ConfigureAwait(false);
if (oldSemanticTokensData == null)
{
var newResultId = _tokensCache.GetNextResultId();
var updatedTokens = new LSP.SemanticTokens { ResultId = newResultId, Data = newSemanticTokensData };
await _tokensCache.UpdateCacheAsync(
request.TextDocument.Uri, updatedTokens, cancellationToken).ConfigureAwait(false);
return new LSP.SemanticTokens { ResultId = newResultId, Data = newSemanticTokensData };
}
var resultId = request.PreviousResultId;
var editArray = ComputeSemanticTokensEdits(oldSemanticTokensData, newSemanticTokensData);
// If we have edits, generate a new ResultId. Otherwise, re-use the previous one.
if (editArray.Length != 0)
{
resultId = _tokensCache.GetNextResultId();
var updatedTokens = new LSP.SemanticTokens { ResultId = resultId, Data = newSemanticTokensData };
await _tokensCache.UpdateCacheAsync(
request.TextDocument.Uri, updatedTokens, cancellationToken).ConfigureAwait(false);
}
var edits = new SemanticTokensDelta
{
Edits = editArray,
ResultId = resultId
};
return edits;
}
/// <summary>
/// Compares two sets of SemanticTokens and returns the edits between them.
/// </summary>
private static LSP.SemanticTokensEdit[] ComputeSemanticTokensEdits(
int[] oldSemanticTokens,
int[] newSemanticTokens)
{
if (oldSemanticTokens.SequenceEqual(newSemanticTokens))
{
return Array.Empty<SemanticTokensEdit>();
}
// We use Roslyn's version of the Myers' Diff Algorithm to compute the minimal edits between
// the old and new tokens. Edits are computed on an int level, with five ints representing
// one token. We compute on int level rather than token level to minimize the amount of
// edits we send back to the client.
var edits = LongestCommonSemanticTokensSubsequence.GetEdits(oldSemanticTokens, newSemanticTokens);
var processedEdits = ProcessEdits(newSemanticTokens, edits.ToArray());
return processedEdits;
}
private static LSP.SemanticTokensEdit[] ProcessEdits(
int[] newSemanticTokens,
SequenceEdit[] edits)
{
using var _ = ArrayBuilder<RoslynSemanticTokensEdit>.GetInstance(out var results);
var insertIndex = 0;
// Go through and attempt to combine individual edits into larger edits. By default,
// edits are returned from Roslyn's LCS ordered from largest -> smallest index.
// However, to simplify computation, we process edits ordered from smallest -> largest
// index.
for (var i = edits.Length - 1; i >= 0; i--)
{
var edit = edits[i];
// Retrieve the most recent edit to see if it can be expanded.
var editInProgress = results.Count > 0 ? results[^1] : null;
switch (edit.Kind)
{
case EditKind.Delete:
// If we have a deletion edit, we should see if there's an edit in progress
// we can combine with. If not, we'll generate a new edit.
//
// Note we've set up the logic such that deletion edits can be combined with
// an insertion edit in progress, but not vice versa. This works out
// because the edits list passed into this method always orders the
// insertions for a given start index before deletions.
if (editInProgress != null &&
editInProgress.Start + editInProgress.DeleteCount == edit.OldIndex)
{
editInProgress.DeleteCount++;
}
else
{
results.Add(new RoslynSemanticTokensEdit
{
Start = edit.OldIndex,
DeleteCount = 1,
});
}
break;
case EditKind.Insert:
// If we have an insertion edit, we should see if there's an insertion edit
// in progress we can combine with. If not, we'll generate a new edit.
//
// As mentioned above, we only combine insertion edits with in-progress
// insertion edits.
if (editInProgress != null &&
editInProgress.Data != null &&
editInProgress.Data.Count > 0 &&
editInProgress.Start == insertIndex)
{
editInProgress.Data.Add(newSemanticTokens[edit.NewIndex]);
}
else
{
var semanticTokensEdit = new RoslynSemanticTokensEdit
{
Start = insertIndex,
Data = new List<int>
{
newSemanticTokens[edit.NewIndex],
},
DeleteCount = 0,
};
results.Add(semanticTokensEdit);
}
break;
case EditKind.Update:
// For EditKind.Inserts, we need to keep track of where in the old sequence we should be
// inserting. This location is based off the location of the previous update.
insertIndex = edit.OldIndex + 1;
break;
default:
throw new InvalidOperationException("Only EditKind.Insert and EditKind.Delete are valid.");
}
}
var processedResults = results.Select(e => e.ToSemanticTokensEdit());
return processedResults.ToArray();
}
private sealed class LongestCommonSemanticTokensSubsequence : LongestCommonSubsequence<int[]>
{
private static readonly LongestCommonSemanticTokensSubsequence s_instance = new();
protected override bool ItemsEqual(
int[] oldSemanticTokens, int oldIndex,
int[] newSemanticTokens, int newIndex)
=> oldSemanticTokens[oldIndex] == newSemanticTokens[newIndex];
public static IEnumerable<SequenceEdit> GetEdits(int[] oldSemanticTokens, int[] newSemanticTokens)
{
try
{
var edits = s_instance.GetEdits(
oldSemanticTokens, oldSemanticTokens.Length, newSemanticTokens, newSemanticTokens.Length);
return edits;
}
catch (OutOfMemoryException e) when (FatalError.ReportAndCatch(e))
{
// The algorithm is superlinear in memory usage so we might potentially run out in rare cases.
// Report telemetry and return no edits.
return SpecializedCollections.EmptyEnumerable<SequenceEdit>();
}
}
}
// We need to have a shim class because SemanticTokensEdit.Data is an array type, so if we
// operate on it directly then every time we append an element we're allocating a new array.
private class RoslynSemanticTokensEdit
{
/// <summary>
/// Index where edit begins in the original sequence.
/// </summary>
public int Start { get; set; }
/// <summary>
/// Number of values to delete from tokens array.
/// </summary>
public int DeleteCount { get; set; }
/// <summary>
/// Values to add to tokens array.
/// </summary>
public IList<int>? Data { get; set; }
public SemanticTokensEdit ToSemanticTokensEdit()
{
return new SemanticTokensEdit
{
Data = Data?.ToArray(),
Start = Start,
DeleteCount = DeleteCount,
};
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
/// <summary>
/// Computes the semantic tokens edits for a file. Clients may make edit requests on a timer,
/// or every time an edit is made by the user.
/// </summary>
internal class SemanticTokensEditsHandler : IRequestHandler<LSP.SemanticTokensDeltaParams, SumType<LSP.SemanticTokens, LSP.SemanticTokensDelta>>
{
private readonly SemanticTokensCache _tokensCache;
public string Method => LSP.Methods.TextDocumentSemanticTokensFullDeltaName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public SemanticTokensEditsHandler(SemanticTokensCache tokensCache)
{
_tokensCache = tokensCache;
}
public TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensDeltaParams request)
{
Contract.ThrowIfNull(request.TextDocument);
return request.TextDocument;
}
public async Task<SumType<LSP.SemanticTokens, LSP.SemanticTokensDelta>> HandleRequestAsync(
LSP.SemanticTokensDeltaParams request,
RequestContext context,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.TextDocument, "TextDocument is null.");
Contract.ThrowIfNull(request.PreviousResultId, "previousResultId is null.");
Contract.ThrowIfNull(context.Document, "Document is null.");
// Even though we want to ultimately pass edits back to LSP, we still need to compute all semantic tokens,
// both for caching purposes and in order to have a baseline comparison when computing the edits.
var (newSemanticTokensData, isFinalized) = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync(
context.Document, SemanticTokensCache.TokenTypeToIndex,
range: null, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(newSemanticTokensData, "newSemanticTokensData is null.");
// Getting the cached tokens for the document. If we don't have an applicable cached token set,
// we can't calculate edits, so we must return all semantic tokens instead.
var oldSemanticTokensData = await _tokensCache.GetCachedTokensDataAsync(
request.TextDocument.Uri, request.PreviousResultId, cancellationToken).ConfigureAwait(false);
if (oldSemanticTokensData == null)
{
var newResultId = _tokensCache.GetNextResultId();
var updatedTokens = new RoslynSemanticTokens
{
ResultId = newResultId,
Data = newSemanticTokensData,
IsFinalized = isFinalized,
};
if (newSemanticTokensData.Length > 0)
{
await _tokensCache.UpdateCacheAsync(
request.TextDocument.Uri, updatedTokens, cancellationToken).ConfigureAwait(false);
}
return updatedTokens;
}
var editArray = ComputeSemanticTokensEdits(oldSemanticTokensData, newSemanticTokensData);
var resultId = request.PreviousResultId;
// If we have edits, generate a new ResultId. Otherwise, re-use the previous one.
if (editArray.Length != 0)
{
resultId = _tokensCache.GetNextResultId();
if (newSemanticTokensData.Length > 0)
{
var updatedTokens = new RoslynSemanticTokens
{
ResultId = resultId,
Data = newSemanticTokensData,
IsFinalized = isFinalized
};
await _tokensCache.UpdateCacheAsync(
request.TextDocument.Uri, updatedTokens, cancellationToken).ConfigureAwait(false);
}
}
var edits = new RoslynSemanticTokensDelta
{
ResultId = resultId,
Edits = editArray,
IsFinalized = isFinalized
};
return edits;
}
/// <summary>
/// Compares two sets of SemanticTokens and returns the edits between them.
/// </summary>
private static LSP.SemanticTokensEdit[] ComputeSemanticTokensEdits(
int[] oldSemanticTokens,
int[] newSemanticTokens)
{
if (oldSemanticTokens.SequenceEqual(newSemanticTokens))
{
return Array.Empty<SemanticTokensEdit>();
}
// We use Roslyn's version of the Myers' Diff Algorithm to compute the minimal edits between
// the old and new tokens. Edits are computed on an int level, with five ints representing
// one token. We compute on int level rather than token level to minimize the amount of
// edits we send back to the client.
var edits = LongestCommonSemanticTokensSubsequence.GetEdits(oldSemanticTokens, newSemanticTokens);
var processedEdits = ProcessEdits(newSemanticTokens, edits.ToArray());
return processedEdits;
}
private static LSP.SemanticTokensEdit[] ProcessEdits(
int[] newSemanticTokens,
SequenceEdit[] edits)
{
using var _ = ArrayBuilder<RoslynSemanticTokensEdit>.GetInstance(out var results);
var insertIndex = 0;
// Go through and attempt to combine individual edits into larger edits. By default,
// edits are returned from Roslyn's LCS ordered from largest -> smallest index.
// However, to simplify computation, we process edits ordered from smallest -> largest
// index.
for (var i = edits.Length - 1; i >= 0; i--)
{
var edit = edits[i];
// Retrieve the most recent edit to see if it can be expanded.
var editInProgress = results.Count > 0 ? results[^1] : null;
switch (edit.Kind)
{
case EditKind.Delete:
// If we have a deletion edit, we should see if there's an edit in progress
// we can combine with. If not, we'll generate a new edit.
//
// Note we've set up the logic such that deletion edits can be combined with
// an insertion edit in progress, but not vice versa. This works out
// because the edits list passed into this method always orders the
// insertions for a given start index before deletions.
if (editInProgress != null &&
editInProgress.Start + editInProgress.DeleteCount == edit.OldIndex)
{
editInProgress.DeleteCount++;
}
else
{
results.Add(new RoslynSemanticTokensEdit
{
Start = edit.OldIndex,
DeleteCount = 1,
});
}
break;
case EditKind.Insert:
// If we have an insertion edit, we should see if there's an insertion edit
// in progress we can combine with. If not, we'll generate a new edit.
//
// As mentioned above, we only combine insertion edits with in-progress
// insertion edits.
if (editInProgress != null &&
editInProgress.Data != null &&
editInProgress.Data.Count > 0 &&
editInProgress.Start == insertIndex)
{
editInProgress.Data.Add(newSemanticTokens[edit.NewIndex]);
}
else
{
var semanticTokensEdit = new RoslynSemanticTokensEdit
{
Start = insertIndex,
Data = new List<int>
{
newSemanticTokens[edit.NewIndex],
},
DeleteCount = 0,
};
results.Add(semanticTokensEdit);
}
break;
case EditKind.Update:
// For EditKind.Inserts, we need to keep track of where in the old sequence we should be
// inserting. This location is based off the location of the previous update.
insertIndex = edit.OldIndex + 1;
break;
default:
throw new InvalidOperationException("Only EditKind.Insert and EditKind.Delete are valid.");
}
}
var processedResults = results.Select(e => e.ToSemanticTokensEdit());
return processedResults.ToArray();
}
private sealed class LongestCommonSemanticTokensSubsequence : LongestCommonSubsequence<int[]>
{
private static readonly LongestCommonSemanticTokensSubsequence s_instance = new();
protected override bool ItemsEqual(
int[] oldSemanticTokens, int oldIndex,
int[] newSemanticTokens, int newIndex)
=> oldSemanticTokens[oldIndex] == newSemanticTokens[newIndex];
public static IEnumerable<SequenceEdit> GetEdits(int[] oldSemanticTokens, int[] newSemanticTokens)
{
try
{
var edits = s_instance.GetEdits(
oldSemanticTokens, oldSemanticTokens.Length, newSemanticTokens, newSemanticTokens.Length);
return edits;
}
catch (OutOfMemoryException e) when (FatalError.ReportAndCatch(e))
{
// The algorithm is superlinear in memory usage so we might potentially run out in rare cases.
// Report telemetry and return no edits.
return SpecializedCollections.EmptyEnumerable<SequenceEdit>();
}
}
}
// We need to have a shim class because SemanticTokensEdit.Data is an array type, so if we
// operate on it directly then every time we append an element we're allocating a new array.
private class RoslynSemanticTokensEdit
{
/// <summary>
/// Index where edit begins in the original sequence.
/// </summary>
public int Start { get; set; }
/// <summary>
/// Number of values to delete from tokens array.
/// </summary>
public int DeleteCount { get; set; }
/// <summary>
/// Values to add to tokens array.
/// </summary>
public IList<int>? Data { get; set; }
public SemanticTokensEdit ToSemanticTokensEdit()
{
return new SemanticTokensEdit
{
Data = Data?.ToArray(),
Start = Start,
DeleteCount = DeleteCount,
};
}
}
}
}
| 1 |
dotnet/roslyn | 55,976 | [LSP] Semantic tokens: Utilize frozen partial compilations | Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | allisonchou | "2021-08-27T22:11:19Z" | "2021-08-31T21:08:24Z" | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | 1dd98de8b262e5dfe03edbba9858f242da32cadb | [LSP] Semantic tokens: Utilize frozen partial compilations. Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | ./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
/// <summary>
/// Computes the semantic tokens for a whole document.
/// </summary>
/// <remarks>
/// This handler is invoked when a user opens a file. Depending on the size of the file, the full token set may be
/// slow to compute, so the <see cref="SemanticTokensRangeHandler"/> is also called when a file is opened in order
/// to render UI results quickly until this handler finishes running.
/// Unlike the range handler, the whole document handler may be called again if the LSP client finds an edit that
/// is difficult to correctly apply to their tags cache. This allows for reliable recovery from errors and accounts
/// for limitations in the edits application logic.
/// </remarks>
internal class SemanticTokensHandler : IRequestHandler<LSP.SemanticTokensParams, LSP.SemanticTokens>
{
private readonly SemanticTokensCache _tokensCache;
public SemanticTokensHandler(SemanticTokensCache tokensCache)
{
_tokensCache = tokensCache;
}
public string Method => LSP.Methods.TextDocumentSemanticTokensFullName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensParams request)
{
Contract.ThrowIfNull(request.TextDocument);
return request.TextDocument;
}
public async Task<LSP.SemanticTokens> HandleRequestAsync(
LSP.SemanticTokensParams request,
RequestContext context,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.TextDocument, "TextDocument is null.");
Contract.ThrowIfNull(context.Document, "Document is null.");
var resultId = _tokensCache.GetNextResultId();
var tokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync(
context.Document, SemanticTokensCache.TokenTypeToIndex,
range: null, cancellationToken).ConfigureAwait(false);
var tokens = new LSP.SemanticTokens { ResultId = resultId, Data = tokensData };
await _tokensCache.UpdateCacheAsync(request.TextDocument.Uri, tokens, cancellationToken).ConfigureAwait(false);
return tokens;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
/// <summary>
/// Computes the semantic tokens for a whole document.
/// </summary>
/// <remarks>
/// This handler is invoked when a user opens a file. Depending on the size of the file, the full token set may be
/// slow to compute, so the <see cref="SemanticTokensRangeHandler"/> is also called when a file is opened in order
/// to render UI results quickly until this handler finishes running.
/// Unlike the range handler, the whole document handler may be called again if the LSP client finds an edit that
/// is difficult to correctly apply to their tags cache. This allows for reliable recovery from errors and accounts
/// for limitations in the edits application logic.
/// </remarks>
internal class SemanticTokensHandler : IRequestHandler<LSP.SemanticTokensParams, LSP.SemanticTokens>
{
private readonly SemanticTokensCache _tokensCache;
public SemanticTokensHandler(SemanticTokensCache tokensCache)
{
_tokensCache = tokensCache;
}
public string Method => LSP.Methods.TextDocumentSemanticTokensFullName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensParams request)
{
Contract.ThrowIfNull(request.TextDocument);
return request.TextDocument;
}
public async Task<LSP.SemanticTokens> HandleRequestAsync(
LSP.SemanticTokensParams request,
RequestContext context,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.TextDocument, "TextDocument is null.");
Contract.ThrowIfNull(context.Document, "Document is null.");
var resultId = _tokensCache.GetNextResultId();
var (tokensData, isFinalized) = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync(
context.Document, SemanticTokensCache.TokenTypeToIndex,
range: null, cancellationToken).ConfigureAwait(false);
var tokens = new RoslynSemanticTokens { ResultId = resultId, Data = tokensData, IsFinalized = isFinalized };
if (tokensData.Length > 0)
{
await _tokensCache.UpdateCacheAsync(request.TextDocument.Uri, tokens, cancellationToken).ConfigureAwait(false);
}
return tokens;
}
}
}
| 1 |
dotnet/roslyn | 55,976 | [LSP] Semantic tokens: Utilize frozen partial compilations | Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | allisonchou | "2021-08-27T22:11:19Z" | "2021-08-31T21:08:24Z" | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | 1dd98de8b262e5dfe03edbba9858f242da32cadb | [LSP] Semantic tokens: Utilize frozen partial compilations. Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | ./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
internal class SemanticTokensHelpers
{
internal static readonly string[] RoslynCustomTokenTypes =
{
ClassificationTypeNames.ClassName,
ClassificationTypeNames.ConstantName,
ClassificationTypeNames.ControlKeyword,
ClassificationTypeNames.DelegateName,
ClassificationTypeNames.EnumMemberName,
ClassificationTypeNames.EnumName,
ClassificationTypeNames.EventName,
ClassificationTypeNames.ExcludedCode,
ClassificationTypeNames.ExtensionMethodName,
ClassificationTypeNames.FieldName,
ClassificationTypeNames.InterfaceName,
ClassificationTypeNames.LabelName,
ClassificationTypeNames.LocalName,
ClassificationTypeNames.MethodName,
ClassificationTypeNames.ModuleName,
ClassificationTypeNames.NamespaceName,
ClassificationTypeNames.OperatorOverloaded,
ClassificationTypeNames.ParameterName,
ClassificationTypeNames.PropertyName,
// Preprocessor
ClassificationTypeNames.PreprocessorKeyword,
ClassificationTypeNames.PreprocessorText,
ClassificationTypeNames.Punctuation,
ClassificationTypeNames.RecordClassName,
ClassificationTypeNames.RecordStructName,
// Regex
ClassificationTypeNames.RegexAlternation,
ClassificationTypeNames.RegexAnchor,
ClassificationTypeNames.RegexCharacterClass,
ClassificationTypeNames.RegexComment,
ClassificationTypeNames.RegexGrouping,
ClassificationTypeNames.RegexOtherEscape,
ClassificationTypeNames.RegexQuantifier,
ClassificationTypeNames.RegexSelfEscapedCharacter,
ClassificationTypeNames.RegexText,
ClassificationTypeNames.StringEscapeCharacter,
ClassificationTypeNames.StructName,
ClassificationTypeNames.Text,
ClassificationTypeNames.TypeParameterName,
ClassificationTypeNames.VerbatimStringLiteral,
ClassificationTypeNames.WhiteSpace,
// XML
ClassificationTypeNames.XmlDocCommentAttributeName,
ClassificationTypeNames.XmlDocCommentAttributeQuotes,
ClassificationTypeNames.XmlDocCommentAttributeValue,
ClassificationTypeNames.XmlDocCommentCDataSection,
ClassificationTypeNames.XmlDocCommentComment,
ClassificationTypeNames.XmlDocCommentDelimiter,
ClassificationTypeNames.XmlDocCommentEntityReference,
ClassificationTypeNames.XmlDocCommentName,
ClassificationTypeNames.XmlDocCommentProcessingInstruction,
ClassificationTypeNames.XmlDocCommentText,
ClassificationTypeNames.XmlLiteralAttributeName,
ClassificationTypeNames.XmlLiteralAttributeQuotes,
ClassificationTypeNames.XmlLiteralAttributeValue,
ClassificationTypeNames.XmlLiteralCDataSection,
ClassificationTypeNames.XmlLiteralComment,
ClassificationTypeNames.XmlLiteralDelimiter,
ClassificationTypeNames.XmlLiteralEmbeddedExpression,
ClassificationTypeNames.XmlLiteralEntityReference,
ClassificationTypeNames.XmlLiteralName,
ClassificationTypeNames.XmlLiteralProcessingInstruction,
ClassificationTypeNames.XmlLiteralText
};
// TO-DO: Expand this mapping once support for custom token types is added:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1085998
private static readonly Dictionary<string, string> s_classificationTypeToSemanticTokenTypeMap =
new Dictionary<string, string>
{
[ClassificationTypeNames.Comment] = LSP.SemanticTokenTypes.Comment,
[ClassificationTypeNames.Identifier] = LSP.SemanticTokenTypes.Variable,
[ClassificationTypeNames.Keyword] = LSP.SemanticTokenTypes.Keyword,
[ClassificationTypeNames.NumericLiteral] = LSP.SemanticTokenTypes.Number,
[ClassificationTypeNames.Operator] = LSP.SemanticTokenTypes.Operator,
[ClassificationTypeNames.StringLiteral] = LSP.SemanticTokenTypes.String,
};
/// <summary>
/// Returns the semantic tokens data for a given document with an optional range.
/// </summary>
internal static async Task<int[]> ComputeSemanticTokensDataAsync(
Document document,
Dictionary<string, int> tokenTypesToIndex,
LSP.Range? range,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// By default we calculate the tokens for the full document span, although the user
// can pass in a range if they wish.
var textSpan = range == null ? root.FullSpan : ProtocolConversions.RangeToTextSpan(range, text);
var classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(classifiedSpans, "classifiedSpans is null");
// Multi-line tokens are not supported by VS (tracked by https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1265495).
// Roslyn's classifier however can return multi-line classified spans, so we must break these up into single-line spans.
var updatedClassifiedSpans = ConvertMultiLineToSingleLineSpans(text, classifiedSpans.ToArray());
// TO-DO: We should implement support for streaming if LSP adds support for it:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1276300
return ComputeTokens(text.Lines, updatedClassifiedSpans, tokenTypesToIndex);
}
private static ClassifiedSpan[] ConvertMultiLineToSingleLineSpans(SourceText text, ClassifiedSpan[] classifiedSpans)
{
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var updatedClassifiedSpans);
for (var spanIndex = 0; spanIndex < classifiedSpans.Length; spanIndex++)
{
var span = classifiedSpans[spanIndex];
text.GetLinesAndOffsets(span.TextSpan, out var startLine, out var startOffset, out var endLine, out var endOffSet);
// If the start and end of the classified span are not on the same line, we're dealing with a multi-line span.
// Since VS doesn't support multi-line spans/tokens, we need to break the span up into single-line spans.
if (startLine != endLine)
{
spanIndex = ConvertToSingleLineSpan(
text, classifiedSpans, updatedClassifiedSpans, spanIndex, span.ClassificationType,
startLine, startOffset, endLine, endOffSet);
}
else
{
// This is already a single-line span, so no modification is necessary.
updatedClassifiedSpans.Add(span);
}
}
return updatedClassifiedSpans.ToArray();
static int ConvertToSingleLineSpan(
SourceText text,
ClassifiedSpan[] originalClassifiedSpans,
ArrayBuilder<ClassifiedSpan> updatedClassifiedSpans,
int spanIndex,
string classificationType,
int startLine,
int startOffset,
int endLine,
int endOffSet)
{
var numLinesInSpan = endLine - startLine + 1;
Contract.ThrowIfTrue(numLinesInSpan < 1);
var updatedSpanIndex = spanIndex;
for (var currentLine = 0; currentLine < numLinesInSpan; currentLine++)
{
TextSpan? textSpan;
// Case 1: First line of span
if (currentLine == 0)
{
var absoluteStartOffset = text.Lines[startLine].Start + startOffset;
var spanLength = text.Lines[startLine].End - absoluteStartOffset;
textSpan = new TextSpan(absoluteStartOffset, spanLength);
}
// Case 2: Any of the span's middle lines
else if (currentLine != numLinesInSpan - 1)
{
textSpan = text.Lines[startLine + currentLine].Span;
}
// Case 3: Last line of span
else
{
textSpan = new TextSpan(text.Lines[endLine].Start, endOffSet);
}
var updatedClassifiedSpan = new ClassifiedSpan(textSpan.Value, classificationType);
updatedClassifiedSpans.Add(updatedClassifiedSpan);
// Since spans are expected to be ordered, when breaking up a multi-line span, we may have to insert
// other spans in-between. For example, we may encounter this case when breaking up a multi-line verbatim
// string literal containing escape characters:
// var x = @"one ""
// two";
// The check below ensures we correctly return the spans in the correct order, i.e. 'one', '""', 'two'.
while (updatedSpanIndex + 1 < originalClassifiedSpans.Length &&
textSpan.Value.Contains(originalClassifiedSpans[updatedSpanIndex + 1].TextSpan))
{
updatedClassifiedSpans.Add(originalClassifiedSpans[updatedSpanIndex + 1]);
updatedSpanIndex++;
}
}
return updatedSpanIndex;
}
}
private static int[] ComputeTokens(
TextLineCollection lines,
ClassifiedSpan[] classifiedSpans,
Dictionary<string, int> tokenTypesToIndex)
{
using var _ = ArrayBuilder<int>.GetInstance(classifiedSpans.Length, out var data);
// We keep track of the last line number and last start character since tokens are
// reported relative to each other.
var lastLineNumber = 0;
var lastStartCharacter = 0;
for (var currentClassifiedSpanIndex = 0; currentClassifiedSpanIndex < classifiedSpans.Length; currentClassifiedSpanIndex++)
{
currentClassifiedSpanIndex = ComputeNextToken(
lines, ref lastLineNumber, ref lastStartCharacter, classifiedSpans,
currentClassifiedSpanIndex, tokenTypesToIndex,
out var deltaLine, out var startCharacterDelta, out var tokenLength,
out var tokenType, out var tokenModifiers);
data.AddRange(deltaLine, startCharacterDelta, tokenLength, tokenType, tokenModifiers);
}
return data.ToArray();
}
private static int ComputeNextToken(
TextLineCollection lines,
ref int lastLineNumber,
ref int lastStartCharacter,
ClassifiedSpan[] classifiedSpans,
int currentClassifiedSpanIndex,
Dictionary<string, int> tokenTypesToIndex,
out int deltaLineOut,
out int startCharacterDeltaOut,
out int tokenLengthOut,
out int tokenTypeOut,
out int tokenModifiersOut)
{
// Each semantic token is represented in LSP by five numbers:
// 1. Token line number delta, relative to the previous token
// 2. Token start character delta, relative to the previous token
// 3. Token length
// 4. Token type (index) - looked up in SemanticTokensLegend.tokenTypes
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
var classifiedSpan = classifiedSpans[currentClassifiedSpanIndex];
var originalTextSpan = classifiedSpan.TextSpan;
var linePosition = lines.GetLinePositionSpan(originalTextSpan).Start;
var lineNumber = linePosition.Line;
// 1. Token line number delta, relative to the previous token
var deltaLine = lineNumber - lastLineNumber;
Contract.ThrowIfTrue(deltaLine < 0, $"deltaLine is less than 0: {deltaLine}");
// 2. Token start character delta, relative to the previous token
// (Relative to 0 or the previous token’s start if they're on the same line)
var deltaStartCharacter = linePosition.Character;
if (lastLineNumber == lineNumber)
{
deltaStartCharacter -= lastStartCharacter;
}
lastLineNumber = lineNumber;
lastStartCharacter = linePosition.Character;
// 3. Token length
var tokenLength = originalTextSpan.Length;
// We currently only have one modifier (static). The logic below will need to change in the future if other
// modifiers are added in the future.
var modifierBits = TokenModifiers.None;
var tokenTypeIndex = 0;
// Classified spans with the same text span should be combined into one token.
while (classifiedSpans[currentClassifiedSpanIndex].TextSpan == originalTextSpan)
{
var classificationType = classifiedSpans[currentClassifiedSpanIndex].ClassificationType;
if (classificationType == ClassificationTypeNames.StaticSymbol)
{
// 4. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.Static;
}
else if (classificationType == ClassificationTypeNames.ReassignedVariable)
{
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.ReassignedVariable;
}
else
{
// 6. Token type - looked up in SemanticTokensLegend.tokenTypes (language server defined mapping
// from integer to LSP token types).
tokenTypeIndex = GetTokenTypeIndex(classificationType, tokenTypesToIndex);
}
// Break out of the loop if we have no more classified spans left, or if the next classified span has
// a different text span than our current text span.
if (currentClassifiedSpanIndex + 1 >= classifiedSpans.Length || classifiedSpans[currentClassifiedSpanIndex + 1].TextSpan != originalTextSpan)
{
break;
}
currentClassifiedSpanIndex++;
}
deltaLineOut = deltaLine;
startCharacterDeltaOut = deltaStartCharacter;
tokenLengthOut = tokenLength;
tokenTypeOut = tokenTypeIndex;
tokenModifiersOut = (int)modifierBits;
return currentClassifiedSpanIndex;
}
private static int GetTokenTypeIndex(string classificationType, Dictionary<string, int> tokenTypesToIndex)
{
if (!s_classificationTypeToSemanticTokenTypeMap.TryGetValue(classificationType, out var tokenTypeStr))
{
tokenTypeStr = classificationType;
}
Contract.ThrowIfFalse(tokenTypesToIndex.TryGetValue(tokenTypeStr, out var tokenTypeIndex), "No matching token type index found.");
return tokenTypeIndex;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
internal class SemanticTokensHelpers
{
internal static readonly string[] RoslynCustomTokenTypes =
{
ClassificationTypeNames.ClassName,
ClassificationTypeNames.ConstantName,
ClassificationTypeNames.ControlKeyword,
ClassificationTypeNames.DelegateName,
ClassificationTypeNames.EnumMemberName,
ClassificationTypeNames.EnumName,
ClassificationTypeNames.EventName,
ClassificationTypeNames.ExcludedCode,
ClassificationTypeNames.ExtensionMethodName,
ClassificationTypeNames.FieldName,
ClassificationTypeNames.InterfaceName,
ClassificationTypeNames.LabelName,
ClassificationTypeNames.LocalName,
ClassificationTypeNames.MethodName,
ClassificationTypeNames.ModuleName,
ClassificationTypeNames.NamespaceName,
ClassificationTypeNames.OperatorOverloaded,
ClassificationTypeNames.ParameterName,
ClassificationTypeNames.PropertyName,
// Preprocessor
ClassificationTypeNames.PreprocessorKeyword,
ClassificationTypeNames.PreprocessorText,
ClassificationTypeNames.Punctuation,
ClassificationTypeNames.RecordClassName,
ClassificationTypeNames.RecordStructName,
// Regex
ClassificationTypeNames.RegexAlternation,
ClassificationTypeNames.RegexAnchor,
ClassificationTypeNames.RegexCharacterClass,
ClassificationTypeNames.RegexComment,
ClassificationTypeNames.RegexGrouping,
ClassificationTypeNames.RegexOtherEscape,
ClassificationTypeNames.RegexQuantifier,
ClassificationTypeNames.RegexSelfEscapedCharacter,
ClassificationTypeNames.RegexText,
ClassificationTypeNames.StringEscapeCharacter,
ClassificationTypeNames.StructName,
ClassificationTypeNames.Text,
ClassificationTypeNames.TypeParameterName,
ClassificationTypeNames.VerbatimStringLiteral,
ClassificationTypeNames.WhiteSpace,
// XML
ClassificationTypeNames.XmlDocCommentAttributeName,
ClassificationTypeNames.XmlDocCommentAttributeQuotes,
ClassificationTypeNames.XmlDocCommentAttributeValue,
ClassificationTypeNames.XmlDocCommentCDataSection,
ClassificationTypeNames.XmlDocCommentComment,
ClassificationTypeNames.XmlDocCommentDelimiter,
ClassificationTypeNames.XmlDocCommentEntityReference,
ClassificationTypeNames.XmlDocCommentName,
ClassificationTypeNames.XmlDocCommentProcessingInstruction,
ClassificationTypeNames.XmlDocCommentText,
ClassificationTypeNames.XmlLiteralAttributeName,
ClassificationTypeNames.XmlLiteralAttributeQuotes,
ClassificationTypeNames.XmlLiteralAttributeValue,
ClassificationTypeNames.XmlLiteralCDataSection,
ClassificationTypeNames.XmlLiteralComment,
ClassificationTypeNames.XmlLiteralDelimiter,
ClassificationTypeNames.XmlLiteralEmbeddedExpression,
ClassificationTypeNames.XmlLiteralEntityReference,
ClassificationTypeNames.XmlLiteralName,
ClassificationTypeNames.XmlLiteralProcessingInstruction,
ClassificationTypeNames.XmlLiteralText
};
// TO-DO: Expand this mapping once support for custom token types is added:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1085998
private static readonly Dictionary<string, string> s_classificationTypeToSemanticTokenTypeMap =
new Dictionary<string, string>
{
[ClassificationTypeNames.Comment] = LSP.SemanticTokenTypes.Comment,
[ClassificationTypeNames.Identifier] = LSP.SemanticTokenTypes.Variable,
[ClassificationTypeNames.Keyword] = LSP.SemanticTokenTypes.Keyword,
[ClassificationTypeNames.NumericLiteral] = LSP.SemanticTokenTypes.Number,
[ClassificationTypeNames.Operator] = LSP.SemanticTokenTypes.Operator,
[ClassificationTypeNames.StringLiteral] = LSP.SemanticTokenTypes.String,
};
/// <summary>
/// Returns the semantic tokens data for a given document with an optional range.
/// </summary>
internal static async Task<(int[], bool isFinalized)> ComputeSemanticTokensDataAsync(
Document document,
Dictionary<string, int> tokenTypesToIndex,
LSP.Range? range,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// By default we calculate the tokens for the full document span, although the user
// can pass in a range if they wish.
var textSpan = range is null ? root.FullSpan : ProtocolConversions.RangeToTextSpan(range, text);
// If the full compilation is not yet available, we'll try getting a partial one. It may contain inaccurate
// results but will speed up how quickly we can respond to the client's request.
var frozenDocument = document.WithFrozenPartialSemantics(cancellationToken);
var semanticModel = await frozenDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(semanticModel);
var isFinalized = document.Project.TryGetCompilation(out var compilation) && compilation == semanticModel.Compilation;
document = frozenDocument;
var classifiedSpans = Classifier.GetClassifiedSpans(semanticModel, textSpan, document.Project.Solution.Workspace, cancellationToken);
Contract.ThrowIfNull(classifiedSpans, "classifiedSpans is null");
// Multi-line tokens are not supported by VS (tracked by https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1265495).
// Roslyn's classifier however can return multi-line classified spans, so we must break these up into single-line spans.
var updatedClassifiedSpans = ConvertMultiLineToSingleLineSpans(text, classifiedSpans.ToArray());
// TO-DO: We should implement support for streaming if LSP adds support for it:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1276300
return (ComputeTokens(text.Lines, updatedClassifiedSpans, tokenTypesToIndex), isFinalized);
}
private static ClassifiedSpan[] ConvertMultiLineToSingleLineSpans(SourceText text, ClassifiedSpan[] classifiedSpans)
{
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var updatedClassifiedSpans);
for (var spanIndex = 0; spanIndex < classifiedSpans.Length; spanIndex++)
{
var span = classifiedSpans[spanIndex];
text.GetLinesAndOffsets(span.TextSpan, out var startLine, out var startOffset, out var endLine, out var endOffSet);
// If the start and end of the classified span are not on the same line, we're dealing with a multi-line span.
// Since VS doesn't support multi-line spans/tokens, we need to break the span up into single-line spans.
if (startLine != endLine)
{
spanIndex = ConvertToSingleLineSpan(
text, classifiedSpans, updatedClassifiedSpans, spanIndex, span.ClassificationType,
startLine, startOffset, endLine, endOffSet);
}
else
{
// This is already a single-line span, so no modification is necessary.
updatedClassifiedSpans.Add(span);
}
}
return updatedClassifiedSpans.ToArray();
static int ConvertToSingleLineSpan(
SourceText text,
ClassifiedSpan[] originalClassifiedSpans,
ArrayBuilder<ClassifiedSpan> updatedClassifiedSpans,
int spanIndex,
string classificationType,
int startLine,
int startOffset,
int endLine,
int endOffSet)
{
var numLinesInSpan = endLine - startLine + 1;
Contract.ThrowIfTrue(numLinesInSpan < 1);
var updatedSpanIndex = spanIndex;
for (var currentLine = 0; currentLine < numLinesInSpan; currentLine++)
{
TextSpan? textSpan;
// Case 1: First line of span
if (currentLine == 0)
{
var absoluteStartOffset = text.Lines[startLine].Start + startOffset;
var spanLength = text.Lines[startLine].End - absoluteStartOffset;
textSpan = new TextSpan(absoluteStartOffset, spanLength);
}
// Case 2: Any of the span's middle lines
else if (currentLine != numLinesInSpan - 1)
{
textSpan = text.Lines[startLine + currentLine].Span;
}
// Case 3: Last line of span
else
{
textSpan = new TextSpan(text.Lines[endLine].Start, endOffSet);
}
var updatedClassifiedSpan = new ClassifiedSpan(textSpan.Value, classificationType);
updatedClassifiedSpans.Add(updatedClassifiedSpan);
// Since spans are expected to be ordered, when breaking up a multi-line span, we may have to insert
// other spans in-between. For example, we may encounter this case when breaking up a multi-line verbatim
// string literal containing escape characters:
// var x = @"one ""
// two";
// The check below ensures we correctly return the spans in the correct order, i.e. 'one', '""', 'two'.
while (updatedSpanIndex + 1 < originalClassifiedSpans.Length &&
textSpan.Value.Contains(originalClassifiedSpans[updatedSpanIndex + 1].TextSpan))
{
updatedClassifiedSpans.Add(originalClassifiedSpans[updatedSpanIndex + 1]);
updatedSpanIndex++;
}
}
return updatedSpanIndex;
}
}
private static int[] ComputeTokens(
TextLineCollection lines,
ClassifiedSpan[] classifiedSpans,
Dictionary<string, int> tokenTypesToIndex)
{
using var _ = ArrayBuilder<int>.GetInstance(classifiedSpans.Length, out var data);
// We keep track of the last line number and last start character since tokens are
// reported relative to each other.
var lastLineNumber = 0;
var lastStartCharacter = 0;
for (var currentClassifiedSpanIndex = 0; currentClassifiedSpanIndex < classifiedSpans.Length; currentClassifiedSpanIndex++)
{
currentClassifiedSpanIndex = ComputeNextToken(
lines, ref lastLineNumber, ref lastStartCharacter, classifiedSpans,
currentClassifiedSpanIndex, tokenTypesToIndex,
out var deltaLine, out var startCharacterDelta, out var tokenLength,
out var tokenType, out var tokenModifiers);
data.AddRange(deltaLine, startCharacterDelta, tokenLength, tokenType, tokenModifiers);
}
return data.ToArray();
}
private static int ComputeNextToken(
TextLineCollection lines,
ref int lastLineNumber,
ref int lastStartCharacter,
ClassifiedSpan[] classifiedSpans,
int currentClassifiedSpanIndex,
Dictionary<string, int> tokenTypesToIndex,
out int deltaLineOut,
out int startCharacterDeltaOut,
out int tokenLengthOut,
out int tokenTypeOut,
out int tokenModifiersOut)
{
// Each semantic token is represented in LSP by five numbers:
// 1. Token line number delta, relative to the previous token
// 2. Token start character delta, relative to the previous token
// 3. Token length
// 4. Token type (index) - looked up in SemanticTokensLegend.tokenTypes
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
var classifiedSpan = classifiedSpans[currentClassifiedSpanIndex];
var originalTextSpan = classifiedSpan.TextSpan;
var linePosition = lines.GetLinePositionSpan(originalTextSpan).Start;
var lineNumber = linePosition.Line;
// 1. Token line number delta, relative to the previous token
var deltaLine = lineNumber - lastLineNumber;
Contract.ThrowIfTrue(deltaLine < 0, $"deltaLine is less than 0: {deltaLine}");
// 2. Token start character delta, relative to the previous token
// (Relative to 0 or the previous token’s start if they're on the same line)
var deltaStartCharacter = linePosition.Character;
if (lastLineNumber == lineNumber)
{
deltaStartCharacter -= lastStartCharacter;
}
lastLineNumber = lineNumber;
lastStartCharacter = linePosition.Character;
// 3. Token length
var tokenLength = originalTextSpan.Length;
// We currently only have one modifier (static). The logic below will need to change in the future if other
// modifiers are added in the future.
var modifierBits = TokenModifiers.None;
var tokenTypeIndex = 0;
// Classified spans with the same text span should be combined into one token.
while (classifiedSpans[currentClassifiedSpanIndex].TextSpan == originalTextSpan)
{
var classificationType = classifiedSpans[currentClassifiedSpanIndex].ClassificationType;
if (classificationType == ClassificationTypeNames.StaticSymbol)
{
// 4. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.Static;
}
else if (classificationType == ClassificationTypeNames.ReassignedVariable)
{
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.ReassignedVariable;
}
else
{
// 6. Token type - looked up in SemanticTokensLegend.tokenTypes (language server defined mapping
// from integer to LSP token types).
tokenTypeIndex = GetTokenTypeIndex(classificationType, tokenTypesToIndex);
}
// Break out of the loop if we have no more classified spans left, or if the next classified span has
// a different text span than our current text span.
if (currentClassifiedSpanIndex + 1 >= classifiedSpans.Length || classifiedSpans[currentClassifiedSpanIndex + 1].TextSpan != originalTextSpan)
{
break;
}
currentClassifiedSpanIndex++;
}
deltaLineOut = deltaLine;
startCharacterDeltaOut = deltaStartCharacter;
tokenLengthOut = tokenLength;
tokenTypeOut = tokenTypeIndex;
tokenModifiersOut = (int)modifierBits;
return currentClassifiedSpanIndex;
}
private static int GetTokenTypeIndex(string classificationType, Dictionary<string, int> tokenTypesToIndex)
{
if (!s_classificationTypeToSemanticTokenTypeMap.TryGetValue(classificationType, out var tokenTypeStr))
{
tokenTypeStr = classificationType;
}
Contract.ThrowIfFalse(tokenTypesToIndex.TryGetValue(tokenTypeStr, out var tokenTypeIndex), "No matching token type index found.");
return tokenTypeIndex;
}
}
}
| 1 |
dotnet/roslyn | 55,976 | [LSP] Semantic tokens: Utilize frozen partial compilations | Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | allisonchou | "2021-08-27T22:11:19Z" | "2021-08-31T21:08:24Z" | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | 1dd98de8b262e5dfe03edbba9858f242da32cadb | [LSP] Semantic tokens: Utilize frozen partial compilations. Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | ./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensRangeHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
/// <summary>
/// Computes the semantic tokens for a given range.
/// </summary>
/// <remarks>
/// When a user opens a file, it can be beneficial to only compute the semantic tokens for the visible range
/// for faster UI rendering.
/// The range handler is only invoked when a file is opened. When the first whole document request completes
/// via <see cref="SemanticTokensHandler"/>, the range handler is not invoked again for the rest of the session.
/// </remarks>
internal class SemanticTokensRangeHandler : IRequestHandler<LSP.SemanticTokensRangeParams, LSP.SemanticTokens>
{
private readonly SemanticTokensCache _tokensCache;
public SemanticTokensRangeHandler(SemanticTokensCache tokensCache)
{
_tokensCache = tokensCache;
}
public string Method => LSP.Methods.TextDocumentSemanticTokensRangeName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensRangeParams request)
{
Contract.ThrowIfNull(request.TextDocument);
return request.TextDocument;
}
public async Task<LSP.SemanticTokens> HandleRequestAsync(
LSP.SemanticTokensRangeParams request,
RequestContext context,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.TextDocument, "TextDocument is null.");
Contract.ThrowIfNull(context.Document, "Document is null.");
var resultId = _tokensCache.GetNextResultId();
// The results from the range handler should not be cached since we don't want to cache
// partial token results. In addition, a range request is only ever called with a whole
// document request, so caching range results is unnecessary since the whole document
// handler will cache the results anyway.
var tokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync(
context.Document, SemanticTokensCache.TokenTypeToIndex,
request.Range, cancellationToken).ConfigureAwait(false);
return new LSP.SemanticTokens { ResultId = resultId, Data = tokensData };
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
/// <summary>
/// Computes the semantic tokens for a given range.
/// </summary>
/// <remarks>
/// When a user opens a file, it can be beneficial to only compute the semantic tokens for the visible range
/// for faster UI rendering.
/// The range handler is only invoked when a file is opened. When the first whole document request completes
/// via <see cref="SemanticTokensHandler"/>, the range handler is not invoked again for the rest of the session.
/// </remarks>
internal class SemanticTokensRangeHandler : IRequestHandler<LSP.SemanticTokensRangeParams, LSP.SemanticTokens>
{
private readonly SemanticTokensCache _tokensCache;
public SemanticTokensRangeHandler(SemanticTokensCache tokensCache)
{
_tokensCache = tokensCache;
}
public string Method => LSP.Methods.TextDocumentSemanticTokensRangeName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensRangeParams request)
{
Contract.ThrowIfNull(request.TextDocument);
return request.TextDocument;
}
public async Task<LSP.SemanticTokens> HandleRequestAsync(
LSP.SemanticTokensRangeParams request,
RequestContext context,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.TextDocument, "TextDocument is null.");
Contract.ThrowIfNull(context.Document, "Document is null.");
var resultId = _tokensCache.GetNextResultId();
// The results from the range handler should not be cached since we don't want to cache
// partial token results. In addition, a range request is only ever called with a whole
// document request, so caching range results is unnecessary since the whole document
// handler will cache the results anyway.
var (tokensData, isFinalized) = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync(
context.Document, SemanticTokensCache.TokenTypeToIndex,
request.Range, cancellationToken).ConfigureAwait(false);
return new RoslynSemanticTokens { ResultId = resultId, Data = tokensData, IsFinalized = isFinalized };
}
}
}
| 1 |
dotnet/roslyn | 55,976 | [LSP] Semantic tokens: Utilize frozen partial compilations | Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | allisonchou | "2021-08-27T22:11:19Z" | "2021-08-31T21:08:24Z" | 4d48ca4f141e79f548bc90c72df26e0f2ebcdd1a | 1dd98de8b262e5dfe03edbba9858f242da32cadb | [LSP] Semantic tokens: Utilize frozen partial compilations. Allows Roslyn's LSP semantic token handlers to utilize frozen compilations to compute tokens. The switch to using frozen compilations is fairly straightforward, however Razor needs to know if we're returning partial tokens or not so they know whether to keep asking us for tokens. To accomplish this, we return a `IsFinalized` property along with our results that Razor can deserialize.
Also modified the handlers' logic to not cache 0-length tokens as it is unnecessary.
Likely should be dual-inserted with the Razor-side PR: https://github.com/dotnet/aspnetcore-tooling/pull/4156 | ./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);
// 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);
// 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);
// 4. Edits handler - no changes (ResultId should remain same)
var editResultsNoChange = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "3");
Assert.Equal("3", ((LSP.SemanticTokensDelta)editResultsNoChange).ResultId);
// 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);
}
[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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.