repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/EventSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an event. /// </summary> internal abstract partial class EventSymbol : Symbol { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal EventSymbol() { } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual EventSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// The type of the event along with its annotations. /// </summary> public abstract TypeWithAnnotations TypeWithAnnotations { get; } /// <summary> /// The type of the event. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? RemoveMethod { get; } internal bool HasAssociatedField { get { return (object?)this.AssociatedField != null; } } /// <summary> /// Returns true if this symbol requires an instance reference as the implicit receiver. This is false if the symbol is static. /// </summary> public virtual bool RequiresInstanceReceiver => !IsStatic; /// <summary> /// True if this is a Windows Runtime-style event. /// /// A normal C# event, "event D E", has accessors /// void add_E(D d) /// void remove_E(D d) /// /// A Windows Runtime event, "event D E", has accessors /// EventRegistrationToken add_E(D d) /// void remove_E(EventRegistrationToken t) /// </summary> public abstract bool IsWindowsRuntimeEvent { get; } /// <summary> /// True if the event itself is excluded from code coverage instrumentation. /// True for source events marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Gets the attributes on event's associated field, if any. /// Returns an empty <see cref="ImmutableArray&lt;AttributeData&gt;"/> if /// there are no attributes. /// </summary> /// <remarks> /// This publicly exposes the attributes of the internal backing field. /// </remarks> public ImmutableArray<CSharpAttributeData> GetFieldAttributes() { return (object?)this.AssociatedField == null ? ImmutableArray<CSharpAttributeData>.Empty : this.AssociatedField.GetAttributes(); } internal virtual FieldSymbol? AssociatedField { get { return null; } } /// <summary> /// Returns the overridden event, or null. /// </summary> public EventSymbol? OverriddenEvent { get { if (this.IsOverride) { if (IsDefinition) { return (EventSymbol)OverriddenOrHiddenMembers.GetOverriddenMember(); } return (EventSymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenEvent); } return null; } } internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { return this.MakeOverriddenOrHiddenMembers(); } } internal bool HidesBaseEventsByName { get { MethodSymbol? accessor = AddMethod ?? RemoveMethod; return (object?)accessor != null && accessor.HidesBaseMethodsByName; } } internal EventSymbol GetLeastOverriddenEvent(NamedTypeSymbol? accessingTypeOpt) { accessingTypeOpt = accessingTypeOpt?.OriginalDefinition; EventSymbol e = this; while (e.IsOverride && !e.HidesBaseEventsByName) { // NOTE: We might not be able to access the overridden event. For example, // // .assembly A // { // InternalsVisibleTo("B") // public class A { internal virtual event Action E { add; remove; } } // } // // .assembly B // { // InternalsVisibleTo("C") // public class B : A { internal override event Action E { add; remove; } } // } // // .assembly C // { // public class C : B { ... new B().E += null ... } // A.E is not accessible from here // } // // See InternalsVisibleToAndStrongNameTests: IvtVirtualCall1, IvtVirtualCall2, IvtVirtual_ParamsAndDynamic. EventSymbol? overridden = e.OverriddenEvent; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object?)overridden == null || (accessingTypeOpt is { } && !AccessCheck.IsSymbolAccessible(overridden, accessingTypeOpt, ref discardedUseSiteInfo))) { break; } e = overridden; } return e; } /// <summary> /// Source: Was the member name qualified with a type name? /// Metadata: Is the member an explicit implementation? /// </summary> /// <remarks> /// Will not always agree with ExplicitInterfaceImplementations.Any() /// (e.g. if binding of the type part of the name fails). /// </remarks> internal virtual bool IsExplicitInterfaceImplementation { get { return ExplicitInterfaceImplementations.Any(); } } /// <summary> /// Returns interface events explicitly implemented by this event. /// </summary> /// <remarks> /// Events imported from metadata can explicitly implement more than one event. /// </remarks> public abstract ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Event; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitEvent(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitEvent(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitEvent(this); } internal EventSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); Debug.Assert(newOwner.IsDefinition || newOwner is SubstitutedNamedTypeSymbol); return newOwner.IsDefinition ? this : new SubstitutedEventSymbol((newOwner as SubstitutedNamedTypeSymbol)!, this); } internal abstract bool MustCallMethodsDirectly { get; } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (this.IsDefinition) { return new UseSiteInfo<AssemblySymbol>(PrimaryDependency); } return this.OriginalDefinition.GetUseSiteInfo(); } internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo<AssemblySymbol> result) { Debug.Assert(this.IsDefinition); // Check event type. if (DeriveUseSiteInfoFromType(ref result, this.TypeWithAnnotations, AllowedRequiredModifierType.None)) { return true; } if (this.ContainingModule.HasUnifiedReferences) { // If the member is in an assembly with unified references, // we check if its definition depends on a type from a unified reference. HashSet<TypeSymbol>? unificationCheckedTypes = null; DiagnosticInfo? diagnosticInfo = result.DiagnosticInfo; if (this.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref diagnosticInfo, this, ref unificationCheckedTypes)) { result = result.AdjustDiagnosticInfo(diagnosticInfo); return true; } result = result.AdjustDiagnosticInfo(diagnosticInfo); } return false; } protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BindToBogus; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo? info = GetUseSiteInfo().DiagnosticInfo; return (object?)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus; } } #endregion protected sealed override ISymbol CreateISymbol() { return new PublicModel.EventSymbol(this); } #region Equality public override bool Equals(Symbol? obj, TypeCompareKind compareKind) { EventSymbol? other = obj as EventSymbol; if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } // This checks if the events have the same definition and the type parameters on the containing types have been // substituted in the same way. return TypeSymbol.Equals(this.ContainingType, other.ContainingType, compareKind) && ReferenceEquals(this.OriginalDefinition, other.OriginalDefinition); } public override int GetHashCode() { int hash = 1; hash = Hash.Combine(this.ContainingType, hash); hash = Hash.Combine(this.Name, hash); return hash; } #endregion Equality } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an event. /// </summary> internal abstract partial class EventSymbol : Symbol { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal EventSymbol() { } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual EventSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// The type of the event along with its annotations. /// </summary> public abstract TypeWithAnnotations TypeWithAnnotations { get; } /// <summary> /// The type of the event. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? RemoveMethod { get; } internal bool HasAssociatedField { get { return (object?)this.AssociatedField != null; } } /// <summary> /// Returns true if this symbol requires an instance reference as the implicit receiver. This is false if the symbol is static. /// </summary> public virtual bool RequiresInstanceReceiver => !IsStatic; /// <summary> /// True if this is a Windows Runtime-style event. /// /// A normal C# event, "event D E", has accessors /// void add_E(D d) /// void remove_E(D d) /// /// A Windows Runtime event, "event D E", has accessors /// EventRegistrationToken add_E(D d) /// void remove_E(EventRegistrationToken t) /// </summary> public abstract bool IsWindowsRuntimeEvent { get; } /// <summary> /// True if the event itself is excluded from code coverage instrumentation. /// True for source events marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Gets the attributes on event's associated field, if any. /// Returns an empty <see cref="ImmutableArray&lt;AttributeData&gt;"/> if /// there are no attributes. /// </summary> /// <remarks> /// This publicly exposes the attributes of the internal backing field. /// </remarks> public ImmutableArray<CSharpAttributeData> GetFieldAttributes() { return (object?)this.AssociatedField == null ? ImmutableArray<CSharpAttributeData>.Empty : this.AssociatedField.GetAttributes(); } internal virtual FieldSymbol? AssociatedField { get { return null; } } /// <summary> /// Returns the overridden event, or null. /// </summary> public EventSymbol? OverriddenEvent { get { if (this.IsOverride) { if (IsDefinition) { return (EventSymbol)OverriddenOrHiddenMembers.GetOverriddenMember(); } return (EventSymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenEvent); } return null; } } internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { return this.MakeOverriddenOrHiddenMembers(); } } internal bool HidesBaseEventsByName { get { MethodSymbol? accessor = AddMethod ?? RemoveMethod; return (object?)accessor != null && accessor.HidesBaseMethodsByName; } } internal EventSymbol GetLeastOverriddenEvent(NamedTypeSymbol? accessingTypeOpt) { accessingTypeOpt = accessingTypeOpt?.OriginalDefinition; EventSymbol e = this; while (e.IsOverride && !e.HidesBaseEventsByName) { // NOTE: We might not be able to access the overridden event. For example, // // .assembly A // { // InternalsVisibleTo("B") // public class A { internal virtual event Action E { add; remove; } } // } // // .assembly B // { // InternalsVisibleTo("C") // public class B : A { internal override event Action E { add; remove; } } // } // // .assembly C // { // public class C : B { ... new B().E += null ... } // A.E is not accessible from here // } // // See InternalsVisibleToAndStrongNameTests: IvtVirtualCall1, IvtVirtualCall2, IvtVirtual_ParamsAndDynamic. EventSymbol? overridden = e.OverriddenEvent; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object?)overridden == null || (accessingTypeOpt is { } && !AccessCheck.IsSymbolAccessible(overridden, accessingTypeOpt, ref discardedUseSiteInfo))) { break; } e = overridden; } return e; } /// <summary> /// Source: Was the member name qualified with a type name? /// Metadata: Is the member an explicit implementation? /// </summary> /// <remarks> /// Will not always agree with ExplicitInterfaceImplementations.Any() /// (e.g. if binding of the type part of the name fails). /// </remarks> internal virtual bool IsExplicitInterfaceImplementation { get { return ExplicitInterfaceImplementations.Any(); } } /// <summary> /// Returns interface events explicitly implemented by this event. /// </summary> /// <remarks> /// Events imported from metadata can explicitly implement more than one event. /// </remarks> public abstract ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Event; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitEvent(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitEvent(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitEvent(this); } internal EventSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); Debug.Assert(newOwner.IsDefinition || newOwner is SubstitutedNamedTypeSymbol); return newOwner.IsDefinition ? this : new SubstitutedEventSymbol((newOwner as SubstitutedNamedTypeSymbol)!, this); } internal abstract bool MustCallMethodsDirectly { get; } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (this.IsDefinition) { return new UseSiteInfo<AssemblySymbol>(PrimaryDependency); } return this.OriginalDefinition.GetUseSiteInfo(); } internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo<AssemblySymbol> result) { Debug.Assert(this.IsDefinition); // Check event type. if (DeriveUseSiteInfoFromType(ref result, this.TypeWithAnnotations, AllowedRequiredModifierType.None)) { return true; } if (this.ContainingModule.HasUnifiedReferences) { // If the member is in an assembly with unified references, // we check if its definition depends on a type from a unified reference. HashSet<TypeSymbol>? unificationCheckedTypes = null; DiagnosticInfo? diagnosticInfo = result.DiagnosticInfo; if (this.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref diagnosticInfo, this, ref unificationCheckedTypes)) { result = result.AdjustDiagnosticInfo(diagnosticInfo); return true; } result = result.AdjustDiagnosticInfo(diagnosticInfo); } return false; } protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BindToBogus; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo? info = GetUseSiteInfo().DiagnosticInfo; return (object?)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus; } } #endregion protected sealed override ISymbol CreateISymbol() { return new PublicModel.EventSymbol(this); } #region Equality public override bool Equals(Symbol? obj, TypeCompareKind compareKind) { EventSymbol? other = obj as EventSymbol; if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } // This checks if the events have the same definition and the type parameters on the containing types have been // substituted in the same way. return TypeSymbol.Equals(this.ContainingType, other.ContainingType, compareKind) && ReferenceEquals(this.OriginalDefinition, other.OriginalDefinition); } public override int GetHashCode() { int hash = 1; hash = Hash.Combine(this.ContainingType, hash); hash = Hash.Combine(this.Name, hash); return hash; } #endregion Equality } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/BuildValidator/LocalSourceResolver.cs
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Rebuild; using Microsoft.CodeAnalysis.Text; using Microsoft.Extensions.Logging; namespace BuildValidator { internal class LocalSourceResolver { internal Options Options { get; } internal ImmutableArray<SourceLinkEntry> SourceLinkEntries { get; } internal ILogger Logger { get; } public LocalSourceResolver(Options options, ImmutableArray<SourceLinkEntry> sourceLinkEntries, ILogger logger) { Options = options; SourceLinkEntries = sourceLinkEntries; Logger = logger; } public SourceText ResolveSource(SourceTextInfo sourceTextInfo) { var originalFilePath = sourceTextInfo.OriginalSourceFilePath; string? onDiskPath = null; foreach (var link in SourceLinkEntries) { if (originalFilePath.StartsWith(link.Prefix, FileNameEqualityComparer.StringComparison)) { onDiskPath = Path.GetFullPath(Path.Combine(Options.SourcePath, originalFilePath.Substring(link.Prefix.Length))); if (File.Exists(onDiskPath)) { break; } } } // if no source links exist to let us prefix the source path, // then assume the file path in the pdb points to the on-disk location of the file. onDiskPath ??= originalFilePath; using var fileStream = File.OpenRead(onDiskPath); var sourceText = SourceText.From(fileStream, encoding: sourceTextInfo.SourceTextEncoding, checksumAlgorithm: SourceHashAlgorithm.Sha256, canBeEmbedded: false); if (!sourceText.GetChecksum().SequenceEqual(sourceTextInfo.Hash)) { throw new Exception($@"File ""{onDiskPath}"" has incorrect hash"); } return sourceText; } } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Rebuild; using Microsoft.CodeAnalysis.Text; using Microsoft.Extensions.Logging; namespace BuildValidator { internal class LocalSourceResolver { internal Options Options { get; } internal ImmutableArray<SourceLinkEntry> SourceLinkEntries { get; } internal ILogger Logger { get; } public LocalSourceResolver(Options options, ImmutableArray<SourceLinkEntry> sourceLinkEntries, ILogger logger) { Options = options; SourceLinkEntries = sourceLinkEntries; Logger = logger; } public SourceText ResolveSource(SourceTextInfo sourceTextInfo) { var originalFilePath = sourceTextInfo.OriginalSourceFilePath; string? onDiskPath = null; foreach (var link in SourceLinkEntries) { if (originalFilePath.StartsWith(link.Prefix, FileNameEqualityComparer.StringComparison)) { onDiskPath = Path.GetFullPath(Path.Combine(Options.SourcePath, originalFilePath.Substring(link.Prefix.Length))); if (File.Exists(onDiskPath)) { break; } } } // if no source links exist to let us prefix the source path, // then assume the file path in the pdb points to the on-disk location of the file. onDiskPath ??= originalFilePath; using var fileStream = File.OpenRead(onDiskPath); var sourceText = SourceText.From(fileStream, encoding: sourceTextInfo.SourceTextEncoding, checksumAlgorithm: SourceHashAlgorithm.Sha256, canBeEmbedded: false); if (!sourceText.GetChecksum().SequenceEqual(sourceTextInfo.Hash)) { throw new Exception($@"File ""{onDiskPath}"" has incorrect hash"); } return sourceText; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Diagnostics/DiagnosticsHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.RegularExpressions; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class DiagnosticsHelper { private static TextSpan FindSpan(string source, string pattern) { var match = Regex.Match(source, pattern); Assert.True(match.Success, "Could not find a match for \"" + pattern + "\" in:" + Environment.NewLine + source); return new TextSpan(match.Index, match.Length); } private static void VerifyDiagnostics(IEnumerable<Diagnostic> actualDiagnostics, params string[] expectedDiagnosticIds) { var actualDiagnosticIds = actualDiagnostics.Select(d => d.Id); Assert.True(expectedDiagnosticIds.SequenceEqual(actualDiagnosticIds), Environment.NewLine + "Expected: " + string.Join(", ", expectedDiagnosticIds) + Environment.NewLine + "Actual: " + string.Join(", ", actualDiagnosticIds)); } public static void VerifyDiagnostics(SemanticModel model, string source, string pattern, params string[] expectedDiagnosticIds) { VerifyDiagnostics(model.GetDiagnostics(FindSpan(source, pattern)), expectedDiagnosticIds); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.RegularExpressions; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class DiagnosticsHelper { private static TextSpan FindSpan(string source, string pattern) { var match = Regex.Match(source, pattern); Assert.True(match.Success, "Could not find a match for \"" + pattern + "\" in:" + Environment.NewLine + source); return new TextSpan(match.Index, match.Length); } private static void VerifyDiagnostics(IEnumerable<Diagnostic> actualDiagnostics, params string[] expectedDiagnosticIds) { var actualDiagnosticIds = actualDiagnostics.Select(d => d.Id); Assert.True(expectedDiagnosticIds.SequenceEqual(actualDiagnosticIds), Environment.NewLine + "Expected: " + string.Join(", ", expectedDiagnosticIds) + Environment.NewLine + "Actual: " + string.Join(", ", actualDiagnosticIds)); } public static void VerifyDiagnostics(SemanticModel model, string source, string pattern, params string[] expectedDiagnosticIds) { VerifyDiagnostics(model.GetDiagnostics(FindSpan(source, pattern)), expectedDiagnosticIds); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_IEquatable_EqualsMethodSymbol.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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousType_IEquatable_EqualsMethodSymbol Inherits SynthesizedRegularMethodBase Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _interfaceMethod As ImmutableArray(Of MethodSymbol) Public Sub New(container As AnonymousTypeTemplateSymbol, interfaceMethod As MethodSymbol) MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectEquals) _parameters = ImmutableArray.Create(Of ParameterSymbol)(New SynthesizedParameterSimpleSymbol(Me, container, 0, "val")) _interfaceMethod = ImmutableArray.Create(interfaceMethod) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return Me._parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return _interfaceMethod End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_Boolean End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousType_IEquatable_EqualsMethodSymbol Inherits SynthesizedRegularMethodBase Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _interfaceMethod As ImmutableArray(Of MethodSymbol) Public Sub New(container As AnonymousTypeTemplateSymbol, interfaceMethod As MethodSymbol) MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectEquals) _parameters = ImmutableArray.Create(Of ParameterSymbol)(New SynthesizedParameterSimpleSymbol(Me, container, 0, "val")) _interfaceMethod = ImmutableArray.Create(interfaceMethod) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return Me._parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return _interfaceMethod End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_Boolean End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Platform/CoreClr/SharedConsoleOutWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NETCOREAPP using System; using System.IO; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.CoreClr { internal static class SharedConsole { private static TextWriter s_savedConsoleOut; private static TextWriter s_savedConsoleError; private static AsyncLocal<StringWriter> s_currentOut; private static AsyncLocal<StringWriter> s_currentError; internal static void OverrideConsole() { s_savedConsoleOut = Console.Out; s_savedConsoleError = Console.Error; s_currentOut = new AsyncLocal<StringWriter>(); s_currentError = new AsyncLocal<StringWriter>(); Console.SetOut(new SharedConsoleOutWriter()); Console.SetError(new SharedConsoleErrorWriter()); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { var outputWriter = new CappedStringWriter(expectedLength); var errorOutputWriter = new CappedStringWriter(expectedLength); var savedOutput = s_currentOut.Value; var savedError = s_currentError.Value; try { s_currentOut.Value = outputWriter; s_currentError.Value = errorOutputWriter; action(); } finally { s_currentOut.Value = savedOutput; s_currentError.Value = savedError; } output = outputWriter.ToString(); errorOutput = errorOutputWriter.ToString(); } private sealed class SharedConsoleOutWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentOut.Value ?? s_savedConsoleOut; } private sealed class SharedConsoleErrorWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentError.Value ?? s_savedConsoleError; } private abstract class SharedConsoleWriter : TextWriter { public override Encoding Encoding => Underlying.Encoding; public abstract TextWriter Underlying { get; } public override void Write(char value) => Underlying.Write(value); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NETCOREAPP using System; using System.IO; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.CoreClr { internal static class SharedConsole { private static TextWriter s_savedConsoleOut; private static TextWriter s_savedConsoleError; private static AsyncLocal<StringWriter> s_currentOut; private static AsyncLocal<StringWriter> s_currentError; internal static void OverrideConsole() { s_savedConsoleOut = Console.Out; s_savedConsoleError = Console.Error; s_currentOut = new AsyncLocal<StringWriter>(); s_currentError = new AsyncLocal<StringWriter>(); Console.SetOut(new SharedConsoleOutWriter()); Console.SetError(new SharedConsoleErrorWriter()); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { var outputWriter = new CappedStringWriter(expectedLength); var errorOutputWriter = new CappedStringWriter(expectedLength); var savedOutput = s_currentOut.Value; var savedError = s_currentError.Value; try { s_currentOut.Value = outputWriter; s_currentError.Value = errorOutputWriter; action(); } finally { s_currentOut.Value = savedOutput; s_currentError.Value = savedError; } output = outputWriter.ToString(); errorOutput = errorOutputWriter.ToString(); } private sealed class SharedConsoleOutWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentOut.Value ?? s_savedConsoleOut; } private sealed class SharedConsoleErrorWriter : SharedConsoleWriter { public override TextWriter Underlying => s_currentError.Value ?? s_savedConsoleError; } private abstract class SharedConsoleWriter : TextWriter { public override Encoding Encoding => Underlying.Encoding; public abstract TextWriter Underlying { get; } public override void Write(char value) => Underlying.Write(value); } } } #endif
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.pt-BR.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="pt-BR" original="../CSharpWorkspaceResources.resx"> <body> <trans-unit id="Indentation_preferences"> <source>Indentation preferences</source> <target state="translated">Preferências de recuo</target> <note /> </trans-unit> <trans-unit id="No_available_location_found_to_add_statements_to"> <source>No available location found to add statements to.</source> <target state="translated">Nenhum local disponível encontrado para adicionar instruções.</target> <note /> </trans-unit> <trans-unit id="Namespace_can_not_be_added_in_this_destination"> <source>Namespace can not be added in this destination.</source> <target state="translated">Namespace não pode ser adicionado nesse destino.</target> <note /> </trans-unit> <trans-unit id="Node_does_not_descend_from_root"> <source>Node does not descend from root.</source> <target state="translated">Nó não deriva da raiz.</target> <note /> </trans-unit> <trans-unit id="Node_not_in_parent_s_child_list"> <source>Node not in parent's child list</source> <target state="translated">Nó não está na lista de filhos do pai</target> <note /> </trans-unit> <trans-unit id="Remove_and_Sort_Usings"> <source>R&amp;emove and Sort Usings</source> <target state="translated">R&amp;emover e Classificar Usos</target> <note /> </trans-unit> <trans-unit id="Sort_Usings"> <source>&amp;Sort Usings</source> <target state="translated">Cla&amp;ssificar Usos</target> <note /> </trans-unit> <trans-unit id="Space_preferences"> <source>Space preferences</source> <target state="translated">Preferências de espaço</target> <note /> </trans-unit> <trans-unit id="Trivia_is_not_associated_with_token"> <source>Trivia is not associated with token</source> <target state="translated">Trívia não está associada a token</target> <note /> </trans-unit> <trans-unit id="Cannot_retrieve_the_Span_of_a_null_syntax_reference"> <source>Cannot retrieve the Span of a null syntax reference.</source> <target state="translated">Não é possível recuperar a Extensão de uma referência de sintaxe nula.</target> <note /> </trans-unit> <trans-unit id="Only_attributes_constructor_initializers_expressions_or_statements_can_be_made_explicit"> <source>Only attributes, constructor initializers, expressions or statements can be made explicit</source> <target state="translated">Somente atributos, inicializadores de construtor, expressões ou instruções podem ser tornados explícitos</target> <note /> </trans-unit> <trans-unit id="Implement_Interface"> <source>Implement Interface</source> <target state="translated">Implementar a interface</target> <note /> </trans-unit> <trans-unit id="Wrapping_preferences"> <source>Wrapping preferences</source> <target state="translated">Preferências de quebra de linha</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="pt-BR" original="../CSharpWorkspaceResources.resx"> <body> <trans-unit id="Indentation_preferences"> <source>Indentation preferences</source> <target state="translated">Preferências de recuo</target> <note /> </trans-unit> <trans-unit id="No_available_location_found_to_add_statements_to"> <source>No available location found to add statements to.</source> <target state="translated">Nenhum local disponível encontrado para adicionar instruções.</target> <note /> </trans-unit> <trans-unit id="Namespace_can_not_be_added_in_this_destination"> <source>Namespace can not be added in this destination.</source> <target state="translated">Namespace não pode ser adicionado nesse destino.</target> <note /> </trans-unit> <trans-unit id="Node_does_not_descend_from_root"> <source>Node does not descend from root.</source> <target state="translated">Nó não deriva da raiz.</target> <note /> </trans-unit> <trans-unit id="Node_not_in_parent_s_child_list"> <source>Node not in parent's child list</source> <target state="translated">Nó não está na lista de filhos do pai</target> <note /> </trans-unit> <trans-unit id="Remove_and_Sort_Usings"> <source>R&amp;emove and Sort Usings</source> <target state="translated">R&amp;emover e Classificar Usos</target> <note /> </trans-unit> <trans-unit id="Sort_Usings"> <source>&amp;Sort Usings</source> <target state="translated">Cla&amp;ssificar Usos</target> <note /> </trans-unit> <trans-unit id="Space_preferences"> <source>Space preferences</source> <target state="translated">Preferências de espaço</target> <note /> </trans-unit> <trans-unit id="Trivia_is_not_associated_with_token"> <source>Trivia is not associated with token</source> <target state="translated">Trívia não está associada a token</target> <note /> </trans-unit> <trans-unit id="Cannot_retrieve_the_Span_of_a_null_syntax_reference"> <source>Cannot retrieve the Span of a null syntax reference.</source> <target state="translated">Não é possível recuperar a Extensão de uma referência de sintaxe nula.</target> <note /> </trans-unit> <trans-unit id="Only_attributes_constructor_initializers_expressions_or_statements_can_be_made_explicit"> <source>Only attributes, constructor initializers, expressions or statements can be made explicit</source> <target state="translated">Somente atributos, inicializadores de construtor, expressões ou instruções podem ser tornados explícitos</target> <note /> </trans-unit> <trans-unit id="Implement_Interface"> <source>Implement Interface</source> <target state="translated">Implementar a interface</target> <note /> </trans-unit> <trans-unit id="Wrapping_preferences"> <source>Wrapping preferences</source> <target state="translated">Preferências de quebra de linha</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Classification/ClassificationHelpers.cs
// Licensed to the .NET Foundation under one or more 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.Classification; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal static class ClassificationHelpers { private const string FromKeyword = "from"; private const string VarKeyword = "var"; private const string UnmanagedKeyword = "unmanaged"; private const string NotNullKeyword = "notnull"; private const string DynamicKeyword = "dynamic"; private const string AwaitKeyword = "await"; /// <summary> /// Determine the classification type for a given token. /// </summary> /// <param name="token">The token.</param> /// <returns>The correct syntactic classification for the token.</returns> public static string? GetClassification(SyntaxToken token) { if (IsControlKeyword(token)) { return ClassificationTypeNames.ControlKeyword; } else if (SyntaxFacts.IsKeywordKind(token.Kind()) || token.IsKind(SyntaxKind.DiscardDesignation)) { // When classifying `_`, IsKeywordKind handles UnderscoreToken, but need to additional check for DiscardDesignation return ClassificationTypeNames.Keyword; } else if (SyntaxFacts.IsPunctuation(token.Kind())) { return GetClassificationForPunctuation(token); } else if (token.Kind() == SyntaxKind.IdentifierToken) { return GetClassificationForIdentifier(token); } else if (IsStringToken(token)) { return IsVerbatimStringToken(token) ? ClassificationTypeNames.VerbatimStringLiteral : ClassificationTypeNames.StringLiteral; } else if (token.Kind() == SyntaxKind.NumericLiteralToken) { return ClassificationTypeNames.NumericLiteral; } return null; } private static bool IsControlKeyword(SyntaxToken token) { if (token.Parent is null || !IsControlKeywordKind(token.Kind())) { return false; } return IsControlStatementKind(token.Parent.Kind()); } private static bool IsControlKeywordKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.YieldKeyword: case SyntaxKind.DefaultKeyword: // Include DefaultKeyword as it can be part of a DefaultSwitchLabel case SyntaxKind.InKeyword: // Include InKeyword as it can be part of an ForEachStatement case SyntaxKind.WhenKeyword: // Include WhenKeyword as it can be part of a CatchFilterClause or a pattern WhenClause return true; default: return false; } } private static bool IsControlStatementKind(SyntaxKind kind) { switch (kind) { // Jump Statements case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // Checked Statements case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.SwitchStatement: case SyntaxKind.SwitchSection: case SyntaxKind.CaseSwitchLabel: case SyntaxKind.CasePatternSwitchLabel: case SyntaxKind.DefaultSwitchLabel: case SyntaxKind.TryStatement: case SyntaxKind.CatchClause: case SyntaxKind.CatchFilterClause: case SyntaxKind.FinallyClause: case SyntaxKind.SwitchExpression: case SyntaxKind.ThrowExpression: case SyntaxKind.WhenClause: return true; default: return false; } } private static bool IsStringToken(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken) || token.IsKind(SyntaxKind.CharacterLiteralToken) || token.IsKind(SyntaxKind.InterpolatedStringStartToken) || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || token.IsKind(SyntaxKind.InterpolatedStringEndToken); } private static bool IsVerbatimStringToken(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { return true; } switch (token.Kind()) { case SyntaxKind.InterpolatedVerbatimStringStartToken: return true; case SyntaxKind.InterpolatedStringStartToken: return false; case SyntaxKind.InterpolatedStringEndToken: { return token.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } case SyntaxKind.InterpolatedStringTextToken: { if (!(token.Parent is InterpolatedStringTextSyntax interpolatedStringText)) { return false; } return interpolatedStringText.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } } return false; } private static string? GetClassificationForIdentifier(SyntaxToken token) { if (token.Parent is BaseTypeDeclarationSyntax typeDeclaration && typeDeclaration.Identifier == token) { return GetClassificationForTypeDeclarationIdentifier(token); } else if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl) && delegateDecl.Identifier == token) { return ClassificationTypeNames.DelegateName; } else if (token.Parent.IsKind(SyntaxKind.TypeParameter, out TypeParameterSyntax? typeParameter) && typeParameter.Identifier == token) { return ClassificationTypeNames.TypeParameterName; } else if (token.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.Identifier == token) { return IsExtensionMethod(methodDeclaration) ? ClassificationTypeNames.ExtensionMethodName : ClassificationTypeNames.MethodName; } else if (token.Parent is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(constructorDeclaration.Parent!); } else if (token.Parent is DestructorDeclarationSyntax destructorDeclaration && destructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(destructorDeclaration.Parent!); } else if (token.Parent is LocalFunctionStatementSyntax localFunctionStatement && localFunctionStatement.Identifier == token) { return ClassificationTypeNames.MethodName; } else if (token.Parent is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Identifier == token) { return ClassificationTypeNames.PropertyName; } else if (token.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration && enumMemberDeclaration.Identifier == token) { return ClassificationTypeNames.EnumMemberName; } else if (token.Parent is CatchDeclarationSyntax catchDeclaration && catchDeclaration.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Identifier == token) { var varDecl = variableDeclarator.Parent as VariableDeclarationSyntax; return varDecl?.Parent switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.FieldName, LocalDeclarationStatementSyntax localDeclarationStatement => localDeclarationStatement.IsConst ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.LocalName, EventFieldDeclarationSyntax _ => ClassificationTypeNames.EventName, _ => ClassificationTypeNames.LocalName, }; } else if (token.Parent is SingleVariableDesignationSyntax singleVariableDesignation && singleVariableDesignation.Identifier == token) { var parent = singleVariableDesignation.Parent; // Handle nested Tuple deconstruction while (parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation)) { parent = parent.Parent; } // Checking for DeclarationExpression covers the following cases: // - Out parameters used within a field initializer or within a method. `int.TryParse("1", out var x)` // - Tuple deconstruction. `var (x, _) = (1, 2);` // // Checking for DeclarationPattern covers the following cases: // - Is patterns. `if (foo is Action action)` // - Switch patterns. `case int x when x > 0:` if (parent.IsKind(SyntaxKind.DeclarationExpression) || parent.IsKind(SyntaxKind.DeclarationPattern)) { return ClassificationTypeNames.LocalName; } return ClassificationTypeNames.Identifier; } else if (token.Parent is ParameterSyntax parameterSyntax && parameterSyntax.Identifier == token) { return ClassificationTypeNames.ParameterName; } else if (token.Parent is ForEachStatementSyntax forEachStatementSyntax && forEachStatementSyntax.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is EventDeclarationSyntax eventDeclarationSyntax && eventDeclarationSyntax.Identifier == token) { return ClassificationTypeNames.EventName; } else if (IsActualContextualKeyword(token)) { return ClassificationTypeNames.Keyword; } else if (token.Parent is IdentifierNameSyntax identifierNameSyntax && IsNamespaceName(identifierNameSyntax)) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is ExternAliasDirectiveSyntax externAliasDirectiveSyntax && externAliasDirectiveSyntax.Identifier == token) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is LabeledStatementSyntax labledStatementSyntax && labledStatementSyntax.Identifier == token) { return ClassificationTypeNames.LabelName; } else { return ClassificationTypeNames.Identifier; } } private static string? GetClassificationTypeForConstructorOrDestructorParent(SyntaxNode parentNode) => parentNode.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null }; private static bool IsNamespaceName(IdentifierNameSyntax identifierSyntax) { var parent = identifierSyntax.Parent; while (parent is QualifiedNameSyntax) parent = parent.Parent; return parent is BaseNamespaceDeclarationSyntax; } public static bool IsStaticallyDeclared(SyntaxToken token) { var parentNode = token.Parent; if (parentNode.IsKind(SyntaxKind.EnumMemberDeclaration)) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } else if (parentNode.IsKind(SyntaxKind.VariableDeclarator)) { // The parent of a VariableDeclarator is a VariableDeclarationSyntax node. // It's parent will be the declaration syntax node. parentNode = parentNode!.Parent!.Parent; // Check if this is a field constant declaration if (parentNode.GetModifiers().Any(SyntaxKind.ConstKeyword)) { return true; } } return parentNode.GetModifiers().Any(SyntaxKind.StaticKeyword); } private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration) => methodDeclaration.ParameterList.Parameters.FirstOrDefault()?.Modifiers.Any(SyntaxKind.ThisKeyword) == true; private static string? GetClassificationForTypeDeclarationIdentifier(SyntaxToken identifier) => identifier.Parent!.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.EnumDeclaration => ClassificationTypeNames.EnumName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.InterfaceDeclaration => ClassificationTypeNames.InterfaceName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null, }; private static string GetClassificationForPunctuation(SyntaxToken token) { if (token.Kind().IsOperator()) { // special cases... switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: // the < and > tokens of a type parameter list or function pointer parameter // list should be classified as punctuation; otherwise, they're operators. if (token.Parent != null) { if (token.Parent.Kind() == SyntaxKind.TypeParameterList || token.Parent.Kind() == SyntaxKind.TypeArgumentList || token.Parent.Kind() == SyntaxKind.FunctionPointerParameterList) { return ClassificationTypeNames.Punctuation; } } break; case SyntaxKind.ColonToken: // the : for inheritance/implements or labels should be classified as // punctuation; otherwise, it's from a conditional operator. if (token.Parent != null) { if (token.Parent.Kind() != SyntaxKind.ConditionalExpression) { return ClassificationTypeNames.Punctuation; } } break; } return ClassificationTypeNames.Operator; } else { return ClassificationTypeNames.Punctuation; } } private static bool IsOperator(this SyntaxKind kind) { switch (kind) { case SyntaxKind.TildeToken: case SyntaxKind.ExclamationToken: case SyntaxKind.PercentToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.AsteriskToken: case SyntaxKind.MinusToken: case SyntaxKind.PlusToken: case SyntaxKind.EqualsToken: case SyntaxKind.BarToken: case SyntaxKind.ColonToken: case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.SlashToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.ColonColonToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: return true; default: return false; } } private static bool IsActualContextualKeyword(SyntaxToken token) { if (token.Parent.IsKind(SyntaxKind.LabeledStatement, out LabeledStatementSyntax? statement) && statement.Identifier == token) { return false; } // Ensure that the text and value text are the same. Otherwise, the identifier might // be escaped. I.e. "var", but not "@var" if (token.ToString() != token.ValueText) { return false; } // Standard cases. We can just check the parent and see if we're // in the right position to be considered a contextual keyword if (token.Parent != null) { switch (token.ValueText) { case AwaitKeyword: return token.GetNextToken(includeZeroWidth: true).IsMissing; case FromKeyword: var fromClause = token.Parent.FirstAncestorOrSelf<FromClauseSyntax>(); return fromClause != null && fromClause.FromKeyword == token; case VarKeyword: // var if (token.Parent is IdentifierNameSyntax && token.Parent?.Parent is ExpressionStatementSyntax) { return true; } // we allow var any time it looks like a variable declaration, and is not in a // field or event field. return token.Parent is IdentifierNameSyntax && token.Parent.Parent is VariableDeclarationSyntax && !(token.Parent.Parent.Parent is FieldDeclarationSyntax) && !(token.Parent.Parent.Parent is EventFieldDeclarationSyntax); case UnmanagedKeyword: case NotNullKeyword: return token.Parent is IdentifierNameSyntax && token.Parent.Parent is TypeConstraintSyntax && token.Parent.Parent.Parent is TypeParameterConstraintClauseSyntax; } } return false; } internal static void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var text2 = text.ToString(textSpan); var tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition: textSpan.Start); Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken); } internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan) { // If we marked this as an identifier and it should now be a keyword // (or vice versa), then fix this up and return it. var classificationType = classifiedSpan.ClassificationType; // Check if the token's type has changed. Note: we don't check for "wasPPKeyword && // !isPPKeyword" here. That's because for fault tolerance any identifier will end up // being parsed as a PP keyword eventually, and if we have the check here, the text // flickers between blue and black while typing. See // http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details. var wasKeyword = classificationType == ClassificationTypeNames.Keyword; var wasIdentifier = classificationType == ClassificationTypeNames.Identifier; // We only do this for identifiers/keywords. if (wasKeyword || wasIdentifier) { // Get the current text under the tag. var span = classifiedSpan.TextSpan; var text = rawText.ToString(span); // Now, try to find the token that corresponds to that text. If // we get 0 or 2+ tokens, then we can't do anything with this. // Also, if that text includes trivia, then we can't do anything. var token = SyntaxFactory.ParseToken(text); if (token.Span.Length == span.Length) { // var, dynamic, and unmanaged are not contextual keywords. They are always identifiers // (that we classify as keywords). Because we are just parsing a token we don't // know if we're in the right context for them to be identifiers or keywords. // So, we base on decision on what they were before. i.e. if we had a keyword // before, then assume it stays a keyword if we see 'var', 'dynamic', or 'unmanaged'. var tokenString = token.ToString(); var isKeyword = SyntaxFacts.IsKeywordKind(token.Kind()) || (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None) || (wasKeyword && (tokenString == VarKeyword || tokenString == DynamicKeyword || tokenString == UnmanagedKeyword || tokenString == NotNullKeyword)); var isIdentifier = token.Kind() == SyntaxKind.IdentifierToken; // We only do this for identifiers/keywords. if (isKeyword || isIdentifier) { if ((wasKeyword && !isKeyword) || (wasIdentifier && !isIdentifier)) { // It changed! Return the new type of tagspan. return new ClassifiedSpan( isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span); } } } } // didn't need to do anything to this one. return classifiedSpan; } } }
// Licensed to the .NET Foundation under one or more 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.Classification; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal static class ClassificationHelpers { private const string FromKeyword = "from"; private const string VarKeyword = "var"; private const string UnmanagedKeyword = "unmanaged"; private const string NotNullKeyword = "notnull"; private const string DynamicKeyword = "dynamic"; private const string AwaitKeyword = "await"; /// <summary> /// Determine the classification type for a given token. /// </summary> /// <param name="token">The token.</param> /// <returns>The correct syntactic classification for the token.</returns> public static string? GetClassification(SyntaxToken token) { if (IsControlKeyword(token)) { return ClassificationTypeNames.ControlKeyword; } else if (SyntaxFacts.IsKeywordKind(token.Kind()) || token.IsKind(SyntaxKind.DiscardDesignation)) { // When classifying `_`, IsKeywordKind handles UnderscoreToken, but need to additional check for DiscardDesignation return ClassificationTypeNames.Keyword; } else if (SyntaxFacts.IsPunctuation(token.Kind())) { return GetClassificationForPunctuation(token); } else if (token.Kind() == SyntaxKind.IdentifierToken) { return GetClassificationForIdentifier(token); } else if (IsStringToken(token)) { return IsVerbatimStringToken(token) ? ClassificationTypeNames.VerbatimStringLiteral : ClassificationTypeNames.StringLiteral; } else if (token.Kind() == SyntaxKind.NumericLiteralToken) { return ClassificationTypeNames.NumericLiteral; } return null; } private static bool IsControlKeyword(SyntaxToken token) { if (token.Parent is null || !IsControlKeywordKind(token.Kind())) { return false; } return IsControlStatementKind(token.Parent.Kind()); } private static bool IsControlKeywordKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.YieldKeyword: case SyntaxKind.DefaultKeyword: // Include DefaultKeyword as it can be part of a DefaultSwitchLabel case SyntaxKind.InKeyword: // Include InKeyword as it can be part of an ForEachStatement case SyntaxKind.WhenKeyword: // Include WhenKeyword as it can be part of a CatchFilterClause or a pattern WhenClause return true; default: return false; } } private static bool IsControlStatementKind(SyntaxKind kind) { switch (kind) { // Jump Statements case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // Checked Statements case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.SwitchStatement: case SyntaxKind.SwitchSection: case SyntaxKind.CaseSwitchLabel: case SyntaxKind.CasePatternSwitchLabel: case SyntaxKind.DefaultSwitchLabel: case SyntaxKind.TryStatement: case SyntaxKind.CatchClause: case SyntaxKind.CatchFilterClause: case SyntaxKind.FinallyClause: case SyntaxKind.SwitchExpression: case SyntaxKind.ThrowExpression: case SyntaxKind.WhenClause: return true; default: return false; } } private static bool IsStringToken(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken) || token.IsKind(SyntaxKind.CharacterLiteralToken) || token.IsKind(SyntaxKind.InterpolatedStringStartToken) || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || token.IsKind(SyntaxKind.InterpolatedStringEndToken); } private static bool IsVerbatimStringToken(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { return true; } switch (token.Kind()) { case SyntaxKind.InterpolatedVerbatimStringStartToken: return true; case SyntaxKind.InterpolatedStringStartToken: return false; case SyntaxKind.InterpolatedStringEndToken: { return token.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } case SyntaxKind.InterpolatedStringTextToken: { if (!(token.Parent is InterpolatedStringTextSyntax interpolatedStringText)) { return false; } return interpolatedStringText.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } } return false; } private static string? GetClassificationForIdentifier(SyntaxToken token) { if (token.Parent is BaseTypeDeclarationSyntax typeDeclaration && typeDeclaration.Identifier == token) { return GetClassificationForTypeDeclarationIdentifier(token); } else if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl) && delegateDecl.Identifier == token) { return ClassificationTypeNames.DelegateName; } else if (token.Parent.IsKind(SyntaxKind.TypeParameter, out TypeParameterSyntax? typeParameter) && typeParameter.Identifier == token) { return ClassificationTypeNames.TypeParameterName; } else if (token.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.Identifier == token) { return IsExtensionMethod(methodDeclaration) ? ClassificationTypeNames.ExtensionMethodName : ClassificationTypeNames.MethodName; } else if (token.Parent is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(constructorDeclaration.Parent!); } else if (token.Parent is DestructorDeclarationSyntax destructorDeclaration && destructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(destructorDeclaration.Parent!); } else if (token.Parent is LocalFunctionStatementSyntax localFunctionStatement && localFunctionStatement.Identifier == token) { return ClassificationTypeNames.MethodName; } else if (token.Parent is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Identifier == token) { return ClassificationTypeNames.PropertyName; } else if (token.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration && enumMemberDeclaration.Identifier == token) { return ClassificationTypeNames.EnumMemberName; } else if (token.Parent is CatchDeclarationSyntax catchDeclaration && catchDeclaration.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Identifier == token) { var varDecl = variableDeclarator.Parent as VariableDeclarationSyntax; return varDecl?.Parent switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.FieldName, LocalDeclarationStatementSyntax localDeclarationStatement => localDeclarationStatement.IsConst ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.LocalName, EventFieldDeclarationSyntax _ => ClassificationTypeNames.EventName, _ => ClassificationTypeNames.LocalName, }; } else if (token.Parent is SingleVariableDesignationSyntax singleVariableDesignation && singleVariableDesignation.Identifier == token) { var parent = singleVariableDesignation.Parent; // Handle nested Tuple deconstruction while (parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation)) { parent = parent.Parent; } // Checking for DeclarationExpression covers the following cases: // - Out parameters used within a field initializer or within a method. `int.TryParse("1", out var x)` // - Tuple deconstruction. `var (x, _) = (1, 2);` // // Checking for DeclarationPattern covers the following cases: // - Is patterns. `if (foo is Action action)` // - Switch patterns. `case int x when x > 0:` if (parent.IsKind(SyntaxKind.DeclarationExpression) || parent.IsKind(SyntaxKind.DeclarationPattern)) { return ClassificationTypeNames.LocalName; } return ClassificationTypeNames.Identifier; } else if (token.Parent is ParameterSyntax parameterSyntax && parameterSyntax.Identifier == token) { return ClassificationTypeNames.ParameterName; } else if (token.Parent is ForEachStatementSyntax forEachStatementSyntax && forEachStatementSyntax.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is EventDeclarationSyntax eventDeclarationSyntax && eventDeclarationSyntax.Identifier == token) { return ClassificationTypeNames.EventName; } else if (IsActualContextualKeyword(token)) { return ClassificationTypeNames.Keyword; } else if (token.Parent is IdentifierNameSyntax identifierNameSyntax && IsNamespaceName(identifierNameSyntax)) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is ExternAliasDirectiveSyntax externAliasDirectiveSyntax && externAliasDirectiveSyntax.Identifier == token) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is LabeledStatementSyntax labledStatementSyntax && labledStatementSyntax.Identifier == token) { return ClassificationTypeNames.LabelName; } else { return ClassificationTypeNames.Identifier; } } private static string? GetClassificationTypeForConstructorOrDestructorParent(SyntaxNode parentNode) => parentNode.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null }; private static bool IsNamespaceName(IdentifierNameSyntax identifierSyntax) { var parent = identifierSyntax.Parent; while (parent is QualifiedNameSyntax) parent = parent.Parent; return parent is BaseNamespaceDeclarationSyntax; } public static bool IsStaticallyDeclared(SyntaxToken token) { var parentNode = token.Parent; if (parentNode.IsKind(SyntaxKind.EnumMemberDeclaration)) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } else if (parentNode.IsKind(SyntaxKind.VariableDeclarator)) { // The parent of a VariableDeclarator is a VariableDeclarationSyntax node. // It's parent will be the declaration syntax node. parentNode = parentNode!.Parent!.Parent; // Check if this is a field constant declaration if (parentNode.GetModifiers().Any(SyntaxKind.ConstKeyword)) { return true; } } return parentNode.GetModifiers().Any(SyntaxKind.StaticKeyword); } private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration) => methodDeclaration.ParameterList.Parameters.FirstOrDefault()?.Modifiers.Any(SyntaxKind.ThisKeyword) == true; private static string? GetClassificationForTypeDeclarationIdentifier(SyntaxToken identifier) => identifier.Parent!.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.EnumDeclaration => ClassificationTypeNames.EnumName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.InterfaceDeclaration => ClassificationTypeNames.InterfaceName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null, }; private static string GetClassificationForPunctuation(SyntaxToken token) { if (token.Kind().IsOperator()) { // special cases... switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: // the < and > tokens of a type parameter list or function pointer parameter // list should be classified as punctuation; otherwise, they're operators. if (token.Parent != null) { if (token.Parent.Kind() == SyntaxKind.TypeParameterList || token.Parent.Kind() == SyntaxKind.TypeArgumentList || token.Parent.Kind() == SyntaxKind.FunctionPointerParameterList) { return ClassificationTypeNames.Punctuation; } } break; case SyntaxKind.ColonToken: // the : for inheritance/implements or labels should be classified as // punctuation; otherwise, it's from a conditional operator. if (token.Parent != null) { if (token.Parent.Kind() != SyntaxKind.ConditionalExpression) { return ClassificationTypeNames.Punctuation; } } break; } return ClassificationTypeNames.Operator; } else { return ClassificationTypeNames.Punctuation; } } private static bool IsOperator(this SyntaxKind kind) { switch (kind) { case SyntaxKind.TildeToken: case SyntaxKind.ExclamationToken: case SyntaxKind.PercentToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.AsteriskToken: case SyntaxKind.MinusToken: case SyntaxKind.PlusToken: case SyntaxKind.EqualsToken: case SyntaxKind.BarToken: case SyntaxKind.ColonToken: case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.SlashToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.ColonColonToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: return true; default: return false; } } private static bool IsActualContextualKeyword(SyntaxToken token) { if (token.Parent.IsKind(SyntaxKind.LabeledStatement, out LabeledStatementSyntax? statement) && statement.Identifier == token) { return false; } // Ensure that the text and value text are the same. Otherwise, the identifier might // be escaped. I.e. "var", but not "@var" if (token.ToString() != token.ValueText) { return false; } // Standard cases. We can just check the parent and see if we're // in the right position to be considered a contextual keyword if (token.Parent != null) { switch (token.ValueText) { case AwaitKeyword: return token.GetNextToken(includeZeroWidth: true).IsMissing; case FromKeyword: var fromClause = token.Parent.FirstAncestorOrSelf<FromClauseSyntax>(); return fromClause != null && fromClause.FromKeyword == token; case VarKeyword: // var if (token.Parent is IdentifierNameSyntax && token.Parent?.Parent is ExpressionStatementSyntax) { return true; } // we allow var any time it looks like a variable declaration, and is not in a // field or event field. return token.Parent is IdentifierNameSyntax && token.Parent.Parent is VariableDeclarationSyntax && !(token.Parent.Parent.Parent is FieldDeclarationSyntax) && !(token.Parent.Parent.Parent is EventFieldDeclarationSyntax); case UnmanagedKeyword: case NotNullKeyword: return token.Parent is IdentifierNameSyntax && token.Parent.Parent is TypeConstraintSyntax && token.Parent.Parent.Parent is TypeParameterConstraintClauseSyntax; } } return false; } internal static void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var text2 = text.ToString(textSpan); var tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition: textSpan.Start); Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken); } internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan) { // If we marked this as an identifier and it should now be a keyword // (or vice versa), then fix this up and return it. var classificationType = classifiedSpan.ClassificationType; // Check if the token's type has changed. Note: we don't check for "wasPPKeyword && // !isPPKeyword" here. That's because for fault tolerance any identifier will end up // being parsed as a PP keyword eventually, and if we have the check here, the text // flickers between blue and black while typing. See // http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details. var wasKeyword = classificationType == ClassificationTypeNames.Keyword; var wasIdentifier = classificationType == ClassificationTypeNames.Identifier; // We only do this for identifiers/keywords. if (wasKeyword || wasIdentifier) { // Get the current text under the tag. var span = classifiedSpan.TextSpan; var text = rawText.ToString(span); // Now, try to find the token that corresponds to that text. If // we get 0 or 2+ tokens, then we can't do anything with this. // Also, if that text includes trivia, then we can't do anything. var token = SyntaxFactory.ParseToken(text); if (token.Span.Length == span.Length) { // var, dynamic, and unmanaged are not contextual keywords. They are always identifiers // (that we classify as keywords). Because we are just parsing a token we don't // know if we're in the right context for them to be identifiers or keywords. // So, we base on decision on what they were before. i.e. if we had a keyword // before, then assume it stays a keyword if we see 'var', 'dynamic', or 'unmanaged'. var tokenString = token.ToString(); var isKeyword = SyntaxFacts.IsKeywordKind(token.Kind()) || (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None) || (wasKeyword && (tokenString == VarKeyword || tokenString == DynamicKeyword || tokenString == UnmanagedKeyword || tokenString == NotNullKeyword)); var isIdentifier = token.Kind() == SyntaxKind.IdentifierToken; // We only do this for identifiers/keywords. if (isKeyword || isIdentifier) { if ((wasKeyword && !isKeyword) || (wasIdentifier && !isIdentifier)) { // It changed! Return the new type of tagspan. return new ClassifiedSpan( isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span); } } } } // didn't need to do anything to this one. return classifiedSpan; } } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class CSharpCodeGenerationHelpers { public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>( TDeclarationSyntax result, SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax { return members.Count == 1 ? result.WithAdditionalAnnotations(Formatter.Annotation) : result; } internal static void AddAccessibilityModifiers( Accessibility accessibility, ArrayBuilder<SyntaxToken> tokens, CodeGenerationOptions options, Accessibility defaultAccessibility) { options ??= CodeGenerationOptions.Default; if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility) { return; } switch (accessibility) { case Accessibility.Public: tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Protected: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Private: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.ProtectedAndInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Internal: tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.ProtectedOrInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; } } public static TypeDeclarationSyntax AddMembersTo( TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members) { var syntaxTree = destination.SyntaxTree; destination = ReplaceUnterminatedConstructs(destination); var node = ConditionallyAddFormattingAnnotationTo( destination.EnsureOpenAndCloseBraceTokens().WithMembers(members), members); // Make sure the generated syntax node has same parse option. // e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node. var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options); return (TypeDeclarationSyntax)tree.GetRoot(); } private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination) { const string MultiLineCommentTerminator = "*/"; var lastToken = destination.GetLastToken(); var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia, (t1, t2) => { if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia) { var text = t1.ToString(); if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal)) { return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); } } else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia) { return ReplaceUnterminatedConstructs(t1); } return t1; }); return destination.ReplaceToken(lastToken, updatedToken); } private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia) { var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure(); var tokens = syntax.Tokens; var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct)); var updatedSyntax = syntax.WithTokens(updatedTokens); return SyntaxFactory.Trivia(updatedSyntax); } private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 2 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } else if (token.IsRegularStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 1 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } return token; } public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(); public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is FieldDeclarationSyntax); public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is ConstructorDeclarationSyntax); public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is OperatorDeclarationSyntax || m is ConversionOperatorDeclarationSyntax); public static SyntaxList<TDeclaration> Insert<TDeclaration>( SyntaxList<TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList<bool> availableIndices, Func<SyntaxList<TDeclaration>, TDeclaration> after = null, Func<SyntaxList<TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, options, availableIndices, CSharpDeclarationComparer.WithoutNamesInstance, CSharpDeclarationComparer.WithNamesInstance, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return declarationList.Insert(index, declaration); } private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode => declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any(); public static SyntaxNode GetContextNode( Location location, CancellationToken cancellationToken) { var contextLocation = location as Location; var contextTree = contextLocation != null && contextLocation.IsInSource ? contextLocation.SourceTree : null; return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent; } public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier( IEnumerable<ISymbol> implementations) { var implementation = implementations.FirstOrDefault(); if (implementation == null) { return null; } if (!(implementation.ContainingType.GenerateTypeSyntax() is NameSyntax name)) { return null; } return SyntaxFactory.ExplicitInterfaceSpecifier(name); } public static CodeGenerationDestination GetDestination(SyntaxNode destination) { if (destination != null) { return destination.Kind() switch { SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType, SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit, SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType, SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType, SyntaxKind.FileScopedNamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType, _ => CodeGenerationDestination.Unspecified, }; } return CodeGenerationDestination.Unspecified; } public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>( TSyntaxNode node, ISymbol symbol, CodeGenerationOptions options, CancellationToken cancellationToken = default) where TSyntaxNode : SyntaxNode { if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment())) { return node; } var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken) ? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) : node; return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class CSharpCodeGenerationHelpers { public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>( TDeclarationSyntax result, SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax { return members.Count == 1 ? result.WithAdditionalAnnotations(Formatter.Annotation) : result; } internal static void AddAccessibilityModifiers( Accessibility accessibility, ArrayBuilder<SyntaxToken> tokens, CodeGenerationOptions options, Accessibility defaultAccessibility) { options ??= CodeGenerationOptions.Default; if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility) { return; } switch (accessibility) { case Accessibility.Public: tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Protected: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Private: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.ProtectedAndInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Internal: tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.ProtectedOrInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; } } public static TypeDeclarationSyntax AddMembersTo( TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members) { var syntaxTree = destination.SyntaxTree; destination = ReplaceUnterminatedConstructs(destination); var node = ConditionallyAddFormattingAnnotationTo( destination.EnsureOpenAndCloseBraceTokens().WithMembers(members), members); // Make sure the generated syntax node has same parse option. // e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node. var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options); return (TypeDeclarationSyntax)tree.GetRoot(); } private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination) { const string MultiLineCommentTerminator = "*/"; var lastToken = destination.GetLastToken(); var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia, (t1, t2) => { if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia) { var text = t1.ToString(); if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal)) { return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); } } else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia) { return ReplaceUnterminatedConstructs(t1); } return t1; }); return destination.ReplaceToken(lastToken, updatedToken); } private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia) { var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure(); var tokens = syntax.Tokens; var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct)); var updatedSyntax = syntax.WithTokens(updatedTokens); return SyntaxFactory.Trivia(updatedSyntax); } private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 2 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } else if (token.IsRegularStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 1 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } return token; } public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(); public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is FieldDeclarationSyntax); public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is ConstructorDeclarationSyntax); public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is OperatorDeclarationSyntax || m is ConversionOperatorDeclarationSyntax); public static SyntaxList<TDeclaration> Insert<TDeclaration>( SyntaxList<TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList<bool> availableIndices, Func<SyntaxList<TDeclaration>, TDeclaration> after = null, Func<SyntaxList<TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, options, availableIndices, CSharpDeclarationComparer.WithoutNamesInstance, CSharpDeclarationComparer.WithNamesInstance, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return declarationList.Insert(index, declaration); } private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode => declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any(); public static SyntaxNode GetContextNode( Location location, CancellationToken cancellationToken) { var contextLocation = location as Location; var contextTree = contextLocation != null && contextLocation.IsInSource ? contextLocation.SourceTree : null; return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent; } public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier( IEnumerable<ISymbol> implementations) { var implementation = implementations.FirstOrDefault(); if (implementation == null) { return null; } if (!(implementation.ContainingType.GenerateTypeSyntax() is NameSyntax name)) { return null; } return SyntaxFactory.ExplicitInterfaceSpecifier(name); } public static CodeGenerationDestination GetDestination(SyntaxNode destination) { if (destination != null) { return destination.Kind() switch { SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType, SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit, SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType, SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType, SyntaxKind.FileScopedNamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType, _ => CodeGenerationDestination.Unspecified, }; } return CodeGenerationDestination.Unspecified; } public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>( TSyntaxNode node, ISymbol symbol, CodeGenerationOptions options, CancellationToken cancellationToken = default) where TSyntaxNode : SyntaxNode { if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment())) { return node; } var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken) ? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) : node; return result; } } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageService(typeof(SyntaxGenerator), LanguageNames.CSharp), Shared] internal class CSharpSyntaxGenerator : SyntaxGenerator { // A bit hacky, but we need to actually run ParseToken on the "nameof" text as there's no // other way to get a token back that has the appropriate internal bit set that indicates // this has the .ContextualKind of SyntaxKind.NameOfKeyword. private static readonly IdentifierNameSyntax s_nameOfIdentifier = SyntaxFactory.IdentifierName(SyntaxFactory.ParseToken("nameof")); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpSyntaxGenerator() { } internal override SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; internal override SyntaxTrivia CarriageReturnLineFeed => SyntaxFactory.CarriageReturnLineFeed; internal override bool RequiresExplicitImplementationForInterfaceMembers => false; internal override SyntaxGeneratorInternal SyntaxGeneratorInternal => CSharpSyntaxGeneratorInternal.Instance; internal override SyntaxTrivia Whitespace(string text) => SyntaxFactory.Whitespace(text); internal override SyntaxTrivia SingleLineComment(string text) => SyntaxFactory.Comment("//" + text); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) => SyntaxFactory.SeparatedList<TElement>(list); internal override SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim) { const string InterpolatedVerbatimText = "$@\""; return isVerbatim ? SyntaxFactory.Token(default, SyntaxKind.InterpolatedVerbatimStringStartToken, InterpolatedVerbatimText, InterpolatedVerbatimText, default) : SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken); } internal override SyntaxToken CreateInterpolatedStringEndToken() => SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) => SyntaxFactory.SeparatedList(nodes, separators); internal override SyntaxTrivia Trivia(SyntaxNode node) { if (node is StructuredTriviaSyntax structuredTriviaSyntax) { return SyntaxFactory.Trivia(structuredTriviaSyntax); } throw ExceptionUtilities.UnexpectedValue(node.Kind()); } internal override SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString) { var docTrivia = SyntaxFactory.DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, SyntaxFactory.List(nodes), SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken)); docTrivia = docTrivia.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/// ")) .WithTrailingTrivia(trailingTrivia); if (lastWhitespaceTrivia == default) return docTrivia.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)); return docTrivia.WithTrailingTrivia( SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia); } internal override SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return SyntaxFactory.DocumentationCommentTrivia(documentationCommentTrivia.Kind(), SyntaxFactory.List(content), documentationCommentTrivia.EndOfComment); } return null; } public static readonly SyntaxGenerator Instance = new CSharpSyntaxGenerator(); #region Declarations public override SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.CompilationUnit() .WithUsings(this.AsUsingDirectives(declarations)) .WithMembers(AsNamespaceMembers(declarations)); } private SyntaxList<UsingDirectiveSyntax> AsUsingDirectives(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(this.AsUsingDirective).OfType<UsingDirectiveSyntax>()) : default; } private SyntaxNode AsUsingDirective(SyntaxNode node) { if (node is NameSyntax name) { return this.NamespaceImportDeclaration(name); } return node as UsingDirectiveSyntax; } private static SyntaxList<MemberDeclarationSyntax> AsNamespaceMembers(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(AsNamespaceMember).OfType<MemberDeclarationSyntax>()) : default; } private static SyntaxNode AsNamespaceMember(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return declaration; default: return null; } } public override SyntaxNode NamespaceImportDeclaration(SyntaxNode name) => SyntaxFactory.UsingDirective((NameSyntax)name); public override SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name) => SyntaxFactory.UsingDirective(SyntaxFactory.NameEquals(aliasIdentifierName), (NameSyntax)name); public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.NamespaceDeclaration( (NameSyntax)name, default, this.AsUsingDirectives(declarations), AsNamespaceMembers(declarations)); } public override SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode initializer) { return SyntaxFactory.FieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.FieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( name.ToIdentifierToken(), null, initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null)))); } public override SyntaxNode ParameterDeclaration(string name, SyntaxNode type, SyntaxNode initializer, RefKind refKind) { return SyntaxFactory.Parameter( default, CSharpSyntaxGeneratorInternal.GetParameterModifiers(refKind), (TypeSyntax)type, name.ToIdentifierToken(), initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null); } internal static SyntaxToken GetArgumentModifiers(RefKind refKind) { switch (refKind) { case RefKind.None: case RefKind.In: return default; case RefKind.Out: return SyntaxFactory.Token(SyntaxKind.OutKeyword); case RefKind.Ref: return SyntaxFactory.Token(SyntaxKind.RefKeyword); default: throw ExceptionUtilities.UnexpectedValue(refKind); } } public override SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> statements) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); return SyntaxFactory.MethodDeclaration( attributeLists: default, modifiers: AsModifierList(accessibility, modifiers, SyntaxKind.MethodDeclaration), returnType: returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), explicitInterfaceSpecifier: null, identifier: name.ToIdentifierToken(), typeParameterList: AsTypeParameterList(typeParameters), parameterList: AsParameterList(parameters), constraintClauses: default, body: hasBody ? CreateBlock(statements) : null, expressionBody: null, semicolonToken: !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); } public override SyntaxNode OperatorDeclaration(OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); var returnTypeNode = returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); var parameterList = AsParameterList(parameters); var body = hasBody ? CreateBlock(statements) : null; var semicolon = !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; var modifierList = AsModifierList(accessibility, modifiers, SyntaxKind.OperatorDeclaration); var attributes = default(SyntaxList<AttributeListSyntax>); if (kind == OperatorKind.ImplicitConversion || kind == OperatorKind.ExplicitConversion) { return SyntaxFactory.ConversionOperatorDeclaration( attributes, modifierList, SyntaxFactory.Token(GetTokenKind(kind)), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), returnTypeNode, parameterList, body, semicolon); } else { return SyntaxFactory.OperatorDeclaration( attributes, modifierList, returnTypeNode, SyntaxFactory.Token(SyntaxKind.OperatorKeyword), SyntaxFactory.Token(GetTokenKind(kind)), parameterList, body, semicolon); } } private static SyntaxKind GetTokenKind(OperatorKind kind) => kind switch { OperatorKind.ImplicitConversion => SyntaxKind.ImplicitKeyword, OperatorKind.ExplicitConversion => SyntaxKind.ExplicitKeyword, OperatorKind.Addition => SyntaxKind.PlusToken, OperatorKind.BitwiseAnd => SyntaxKind.AmpersandToken, OperatorKind.BitwiseOr => SyntaxKind.BarToken, OperatorKind.Decrement => SyntaxKind.MinusMinusToken, OperatorKind.Division => SyntaxKind.SlashToken, OperatorKind.Equality => SyntaxKind.EqualsEqualsToken, OperatorKind.ExclusiveOr => SyntaxKind.CaretToken, OperatorKind.False => SyntaxKind.FalseKeyword, OperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, OperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, OperatorKind.Increment => SyntaxKind.PlusPlusToken, OperatorKind.Inequality => SyntaxKind.ExclamationEqualsToken, OperatorKind.LeftShift => SyntaxKind.LessThanLessThanToken, OperatorKind.LessThan => SyntaxKind.LessThanToken, OperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, OperatorKind.LogicalNot => SyntaxKind.ExclamationToken, OperatorKind.Modulus => SyntaxKind.PercentToken, OperatorKind.Multiply => SyntaxKind.AsteriskToken, OperatorKind.OnesComplement => SyntaxKind.TildeToken, OperatorKind.RightShift => SyntaxKind.GreaterThanGreaterThanToken, OperatorKind.Subtraction => SyntaxKind.MinusToken, OperatorKind.True => SyntaxKind.TrueKeyword, OperatorKind.UnaryNegation => SyntaxKind.MinusToken, OperatorKind.UnaryPlus => SyntaxKind.PlusToken, _ => throw new ArgumentException("Unknown operator kind."), }; private static ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.ParameterList(); } public override SyntaxNode ConstructorDeclaration( string name, IEnumerable<SyntaxNode> parameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> baseConstructorArguments, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.ConstructorDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ConstructorDeclaration), (name ?? "ctor").ToIdentifierToken(), AsParameterList(parameters), baseConstructorArguments != null ? SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(baseConstructorArguments.Select(AsArgument)))) : null, CreateBlock(statements)); } public override SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } if (hasGetter) accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); if (hasSetter) accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.PropertyDeclaration( attributeLists: default, AsModifierList(accessibility, actualModifiers, SyntaxKind.PropertyDeclaration), (TypeSyntax)type, explicitInterfaceSpecifier: null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode GetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, accessibility, statements); public override SyntaxNode SetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, accessibility, statements); private static SyntaxNode AccessorDeclaration( SyntaxKind kind, Accessibility accessibility, IEnumerable<SyntaxNode> statements) { var accessor = SyntaxFactory.AccessorDeclaration(kind); accessor = accessor.WithModifiers( AsModifierList(accessibility, DeclarationModifiers.None, SyntaxKind.PropertyDeclaration)); accessor = statements == null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) : accessor.WithBody(CreateBlock(statements)); return accessor; } public override SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations) => declaration switch { PropertyDeclarationSyntax property => property.WithAccessorList(CreateAccessorList(property.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), IndexerDeclarationSyntax indexer => indexer.WithAccessorList(CreateAccessorList(indexer.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), _ => declaration, }; private static AccessorListSyntax CreateAccessorList(AccessorListSyntax accessorListOpt, IEnumerable<SyntaxNode> accessorDeclarations) { var list = SyntaxFactory.List(accessorDeclarations.Cast<AccessorDeclarationSyntax>()); return accessorListOpt == null ? SyntaxFactory.AccessorList(list) : accessorListOpt.WithAccessors(list); } public override SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } else { if (getAccessorStatements == null && hasGetter) { getAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (setAccessorStatements == null && hasSetter) { setAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } if (hasGetter) { accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); } if (hasSetter) { accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); } var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.IndexerDeclaration( default, AsModifierList(accessibility, actualModifiers, SyntaxKind.IndexerDeclaration), (TypeSyntax)type, null, AsBracketedParameterList(parameters), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } private static BracketedParameterListSyntax AsBracketedParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.BracketedParameterList(); } private static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var ad = SyntaxFactory.AccessorDeclaration( kind, statements != null ? CreateBlock(statements) : null); if (statements == null) { ad = ad.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return ad; } public override SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers) { return SyntaxFactory.EventFieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventFieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(name)))); } public override SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> parameters, IEnumerable<SyntaxNode> addAccessorStatements, IEnumerable<SyntaxNode> removeAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); if (modifiers.IsAbstract) { addAccessorStatements = null; removeAccessorStatements = null; } else { if (addAccessorStatements == null) { addAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (removeAccessorStatements == null) { removeAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } accessors.Add(AccessorDeclaration(SyntaxKind.AddAccessorDeclaration, addAccessorStatements)); accessors.Add(AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration, removeAccessorStatements)); return SyntaxFactory.EventDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventDeclaration), (TypeSyntax)type, null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { // C# interface implementations are implicit/not-specified -- so they are just named the name as the interface member return PreserveTrivia(declaration, d => { d = WithInterfaceSpecifier(d, null); d = this.AsImplementation(d, Accessibility.Public); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return d; }); } public override SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { return PreserveTrivia(declaration, d => { d = this.AsImplementation(d, Accessibility.NotApplicable); d = this.WithoutConstraints(d); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return WithInterfaceSpecifier(d, SyntaxFactory.ExplicitInterfaceSpecifier((NameSyntax)interfaceTypeName)); }); } private SyntaxNode WithoutConstraints(SyntaxNode declaration) { if (declaration.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax method)) { if (method.ConstraintClauses.Count > 0) { return this.RemoveNodes(method, method.ConstraintClauses); } } return declaration; } private static SyntaxNode WithInterfaceSpecifier(SyntaxNode declaration, ExplicitInterfaceSpecifierSyntax specifier) => declaration.Kind() switch { SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), _ => declaration, }; private SyntaxNode AsImplementation(SyntaxNode declaration, Accessibility requiredAccess) { declaration = this.WithAccessibility(declaration, requiredAccess); declaration = this.WithModifiers(declaration, this.GetModifiers(declaration) - DeclarationModifiers.Abstract); declaration = WithBodies(declaration); return declaration; } private static SyntaxNode WithBodies(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; return method.Body == null ? method.WithSemicolonToken(default).WithBody(CreateBlock(null)) : method; case SyntaxKind.OperatorDeclaration: var op = (OperatorDeclarationSyntax)declaration; return op.Body == null ? op.WithSemicolonToken(default).WithBody(CreateBlock(null)) : op; case SyntaxKind.ConversionOperatorDeclaration: var cop = (ConversionOperatorDeclarationSyntax)declaration; return cop.Body == null ? cop.WithSemicolonToken(default).WithBody(CreateBlock(null)) : cop; case SyntaxKind.PropertyDeclaration: var prop = (PropertyDeclarationSyntax)declaration; return prop.WithAccessorList(WithBodies(prop.AccessorList)); case SyntaxKind.IndexerDeclaration: var ind = (IndexerDeclarationSyntax)declaration; return ind.WithAccessorList(WithBodies(ind.AccessorList)); case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)declaration; return ev.WithAccessorList(WithBodies(ev.AccessorList)); } return declaration; } private static AccessorListSyntax WithBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(x => WithBody(x)))); private static AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax accessor) { if (accessor.Body == null) { return accessor.WithSemicolonToken(default).WithBody(CreateBlock(null)); } else { return accessor; } } private static AccessorListSyntax WithoutBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(WithoutBody))); private static AccessorDeclarationSyntax WithoutBody(AccessorDeclarationSyntax accessor) => accessor.Body != null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithBody(null) : accessor; public override SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode baseType, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { List<BaseTypeSyntax> baseTypes = null; if (baseType != null || interfaceTypes != null) { baseTypes = new List<BaseTypeSyntax>(); if (baseType != null) { baseTypes.Add(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)); } if (interfaceTypes != null) { baseTypes.AddRange(interfaceTypes.Select(i => SyntaxFactory.SimpleBaseType((TypeSyntax)i))); } if (baseTypes.Count == 0) { baseTypes = null; } } return SyntaxFactory.ClassDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ClassDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), baseTypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(baseTypes)) : null, default, this.AsClassMembers(name, members)); } private SyntaxList<MemberDeclarationSyntax> AsClassMembers(string className, IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(m => this.AsClassMember(m, className)).Where(m => m != null)) : default; } private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: node = ((ConstructorDeclarationSyntax)node).WithIdentifier(className.ToIdentifierToken()); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: node = this.AsIsolatedDeclaration(node); break; } return node as MemberDeclarationSyntax; } public override SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.StructDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.StructDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsClassMembers(name, members)); } public override SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.InterfaceDeclaration( default, AsModifierList(accessibility, DeclarationModifiers.None), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsInterfaceMembers(members)); } private SyntaxList<MemberDeclarationSyntax> AsInterfaceMembers(IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(this.AsInterfaceMember).OfType<MemberDeclarationSyntax>()) : default; } internal override SyntaxNode AsInterfaceMember(SyntaxNode m) { return this.Isolate(m, member => { Accessibility acc; DeclarationModifiers modifiers; switch (member.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member) .WithModifiers(default) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) .WithBody(null); case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)member; return property .WithModifiers(default) .WithAccessorList(WithoutBodies(property.AccessorList)); case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)member; return indexer .WithModifiers(default) .WithAccessorList(WithoutBodies(indexer.AccessorList)); // convert event into field event case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)member; return this.EventDeclaration( ev.Identifier.ValueText, ev.Type, Accessibility.NotApplicable, DeclarationModifiers.None); case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)member; return ef.WithModifiers(default); // convert field into property case SyntaxKind.FieldDeclaration: var f = (FieldDeclarationSyntax)member; SyntaxFacts.GetAccessibilityAndModifiers(f.Modifiers, out acc, out modifiers, out _); return this.AsInterfaceMember( this.PropertyDeclaration(this.GetName(f), this.ClearTrivia(this.GetType(f)), acc, modifiers, getAccessorStatements: null, setAccessorStatements: null)); default: return null; } }); } public override SyntaxNode EnumDeclaration( string name, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> members) { return EnumDeclaration(name, underlyingType: null, accessibility, modifiers, members); } internal override SyntaxNode EnumDeclaration(string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null) { return SyntaxFactory.EnumDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EnumDeclaration), name.ToIdentifierToken(), underlyingType != null ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)underlyingType))) : null, this.AsEnumMembers(members)); } public override SyntaxNode EnumMember(string name, SyntaxNode expression) { return SyntaxFactory.EnumMemberDeclaration( default, name.ToIdentifierToken(), expression != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)expression) : null); } private EnumMemberDeclarationSyntax AsEnumMember(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.IdentifierName: var id = (IdentifierNameSyntax)node; return (EnumMemberDeclarationSyntax)this.EnumMember(id.Identifier.ToString(), null); case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)node; if (fd.Declaration.Variables.Count == 1) { var vd = fd.Declaration.Variables[0]; return (EnumMemberDeclarationSyntax)this.EnumMember(vd.Identifier.ToString(), vd.Initializer?.Value); } break; } return (EnumMemberDeclarationSyntax)node; } private SeparatedSyntaxList<EnumMemberDeclarationSyntax> AsEnumMembers(IEnumerable<SyntaxNode> members) => members != null ? SyntaxFactory.SeparatedList(members.Select(this.AsEnumMember)) : default; public override SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default) { return SyntaxFactory.DelegateDeclaration( default, AsModifierList(accessibility, modifiers), returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), AsParameterList(parameters), default); } public override SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments) => AsAttributeList(SyntaxFactory.Attribute((NameSyntax)name, AsAttributeArgumentList(attributeArguments))); public override SyntaxNode AttributeArgument(string name, SyntaxNode expression) { return name != null ? SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(name.ToIdentifierName()), null, (ExpressionSyntax)expression) : SyntaxFactory.AttributeArgument((ExpressionSyntax)expression); } private static AttributeArgumentListSyntax AsAttributeArgumentList(IEnumerable<SyntaxNode> arguments) { if (arguments != null) { return SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AsAttributeArgument))); } else { return null; } } private static AttributeArgumentSyntax AsAttributeArgument(SyntaxNode node) { if (node is ExpressionSyntax expr) { return SyntaxFactory.AttributeArgument(expr); } if (node is ArgumentSyntax arg && arg.Expression != null) { return SyntaxFactory.AttributeArgument(null, arg.NameColon, arg.Expression); } return (AttributeArgumentSyntax)node; } public override TNode ClearTrivia<TNode>(TNode node) { if (node != null) { return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker); } else { return null; } } private static SyntaxList<AttributeListSyntax> AsAttributeLists(IEnumerable<SyntaxNode> attributes) { if (attributes != null) { return SyntaxFactory.List(attributes.Select(AsAttributeList)); } else { return default; } } private static AttributeListSyntax AsAttributeList(SyntaxNode node) { if (node is AttributeSyntax attr) { return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attr)); } else { return (AttributeListSyntax)node; } } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declAttributes = new(); public override IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration) { if (!s_declAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => !IsReturnAttribute(al)))); } return attrs; } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declReturnAttributes = new(); public override IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration) { if (!s_declReturnAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declReturnAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => IsReturnAttribute(al)))); } return attrs; } private static bool IsReturnAttribute(AttributeListSyntax list) => list.Target?.Identifier.IsKind(SyntaxKind.ReturnKeyword) ?? false; public override SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) => this.Isolate(declaration, d => this.InsertAttributesInternal(d, index, attributes)); private SyntaxNode InsertAttributesInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsAttributeLists(attributes); var existingAttributes = this.GetAttributes(declaration); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(declaration, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(declaration, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = declaration.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(declaration, newList); } } public override SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: return this.Isolate(declaration, d => this.InsertReturnAttributesInternal(d, index, attributes)); default: return declaration; } } private SyntaxNode InsertReturnAttributesInternal(SyntaxNode d, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsReturnAttributes(attributes); var existingAttributes = this.GetReturnAttributes(d); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(d, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(d, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = d.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(d, newList); } } private static IEnumerable<AttributeListSyntax> AsReturnAttributes(IEnumerable<SyntaxNode> attributes) { return AsAttributeLists(attributes) .Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword)))); } private static SyntaxList<AttributeListSyntax> AsAssemblyAttributes(IEnumerable<AttributeListSyntax> attributes) { return SyntaxFactory.List( attributes.Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))))); } public override IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration) { switch (attributeDeclaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)attributeDeclaration; if (list.Attributes.Count == 1) { return this.GetAttributeArguments(list.Attributes[0]); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)attributeDeclaration; if (attr.ArgumentList != null) { return attr.ArgumentList.Arguments; } break; } return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertAttributeArguments(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) => this.Isolate(declaration, d => InsertAttributeArgumentsInternal(d, index, attributeArguments)); private static SyntaxNode InsertAttributeArgumentsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) { var newArgumentList = AsAttributeArgumentList(attributeArguments); var existingArgumentList = GetAttributeArgumentList(declaration); if (existingArgumentList == null) { return WithAttributeArgumentList(declaration, newArgumentList); } else if (newArgumentList != null) { return WithAttributeArgumentList(declaration, existingArgumentList.WithArguments(existingArgumentList.Arguments.InsertRange(index, newArgumentList.Arguments))); } else { return declaration; } } private static AttributeArgumentListSyntax GetAttributeArgumentList(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return list.Attributes[0].ArgumentList; } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.ArgumentList; } return null; } private static SyntaxNode WithAttributeArgumentList(SyntaxNode declaration, AttributeArgumentListSyntax argList) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return ReplaceWithTrivia(declaration, list.Attributes[0], list.Attributes[0].WithArgumentList(argList)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.WithArgumentList(argList); } return declaration; } internal static SyntaxList<AttributeListSyntax> GetAttributeLists(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, StatementSyntax statement => statement.AttributeLists, _ => default, }; private static SyntaxNode WithAttributeLists(SyntaxNode declaration, SyntaxList<AttributeListSyntax> attributeLists) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithAttributeLists(attributeLists), AccessorDeclarationSyntax accessor => accessor.WithAttributeLists(attributeLists), ParameterSyntax parameter => parameter.WithAttributeLists(attributeLists), CompilationUnitSyntax compilationUnit => compilationUnit.WithAttributeLists(AsAssemblyAttributes(attributeLists)), StatementSyntax statement => statement.WithAttributeLists(attributeLists), _ => declaration, }; internal override ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration) => declaration is BaseTypeDeclarationSyntax baseType && baseType.BaseList != null ? ImmutableArray.Create<SyntaxNode>(baseType.BaseList) : ImmutableArray<SyntaxNode>.Empty; public override IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.Usings, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Usings, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) => PreserveTrivia(declaration, d => this.InsertNamespaceImportsInternal(d, index, imports)); private SyntaxNode InsertNamespaceImportsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) { var usingsToInsert = this.AsUsingDirectives(imports); return declaration switch { CompilationUnitSyntax cu => cu.WithUsings(cu.Usings.InsertRange(index, usingsToInsert)), BaseNamespaceDeclarationSyntax nd => nd.WithUsings(nd.Usings.InsertRange(index, usingsToInsert)), _ => declaration, }; } public override IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration) => Flatten(declaration switch { TypeDeclarationSyntax type => type.Members, EnumDeclarationSyntax @enum => @enum.Members, BaseNamespaceDeclarationSyntax @namespace => @namespace.Members, CompilationUnitSyntax compilationUnit => compilationUnit.Members, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }); private static ImmutableArray<SyntaxNode> Flatten(IEnumerable<SyntaxNode> declarations) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var declaration in declarations) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: FlattenDeclaration(builder, declaration, ((FieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.EventFieldDeclaration: FlattenDeclaration(builder, declaration, ((EventFieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.LocalDeclarationStatement: FlattenDeclaration(builder, declaration, ((LocalDeclarationStatementSyntax)declaration).Declaration); break; case SyntaxKind.VariableDeclaration: FlattenDeclaration(builder, declaration, (VariableDeclarationSyntax)declaration); break; case SyntaxKind.AttributeList: var attrList = (AttributeListSyntax)declaration; if (attrList.Attributes.Count > 1) { builder.AddRange(attrList.Attributes); } else { builder.Add(attrList); } break; default: builder.Add(declaration); break; } } return builder.ToImmutableAndFree(); static void FlattenDeclaration(ArrayBuilder<SyntaxNode> builder, SyntaxNode declaration, VariableDeclarationSyntax variableDeclaration) { if (variableDeclaration.Variables.Count > 1) { builder.AddRange(variableDeclaration.Variables); } else { builder.Add(declaration); } } } private static int GetDeclarationCount(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables.Count, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables.Count, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes.Count, _ => 1, }; private static SyntaxNode EnsureRecordDeclarationHasBody(SyntaxNode declaration) { if (declaration is RecordDeclarationSyntax recordDeclaration) { return recordDeclaration .WithSemicolonToken(default) .WithOpenBraceToken(recordDeclaration.OpenBraceToken == default ? SyntaxFactory.Token(SyntaxKind.OpenBraceToken) : recordDeclaration.OpenBraceToken) .WithCloseBraceToken(recordDeclaration.CloseBraceToken == default ? SyntaxFactory.Token(SyntaxKind.CloseBraceToken) : recordDeclaration.CloseBraceToken); } return declaration; } public override SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members) { declaration = EnsureRecordDeclarationHasBody(declaration); var newMembers = this.AsMembersOf(declaration, members); var existingMembers = this.GetMembers(declaration); if (index >= 0 && index < existingMembers.Count) { return this.InsertNodesBefore(declaration, existingMembers[index], newMembers); } else if (existingMembers.Count > 0) { return this.InsertNodesAfter(declaration, existingMembers[existingMembers.Count - 1], newMembers); } else { return declaration switch { TypeDeclarationSyntax type => type.WithMembers(type.Members.AddRange(newMembers)), EnumDeclarationSyntax @enum => @enum.WithMembers(@enum.Members.AddRange(newMembers.OfType<EnumMemberDeclarationSyntax>())), BaseNamespaceDeclarationSyntax @namespace => @namespace.WithMembers(@namespace.Members.AddRange(newMembers)), CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(compilationUnit.Members.AddRange(newMembers)), _ => declaration, }; } } private IEnumerable<MemberDeclarationSyntax> AsMembersOf(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => members?.Select(m => this.AsMemberOf(declaration, m)).OfType<MemberDeclarationSyntax>(); private SyntaxNode AsMemberOf(SyntaxNode declaration, SyntaxNode member) => declaration switch { InterfaceDeclarationSyntax => this.AsInterfaceMember(member), TypeDeclarationSyntax typeDeclaration => this.AsClassMember(member, typeDeclaration.Identifier.Text), EnumDeclarationSyntax => this.AsEnumMember(member), BaseNamespaceDeclarationSyntax => AsNamespaceMember(member), CompilationUnitSyntax => AsNamespaceMember(member), _ => null, }; public override Accessibility GetAccessibility(SyntaxNode declaration) => SyntaxFacts.GetAccessibility(declaration); public override SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility) { if (!SyntaxFacts.CanHaveAccessibility(declaration) && accessibility != Accessibility.NotApplicable) { return declaration; } return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out _, out var modifiers, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } private static readonly DeclarationModifiers s_fieldModifiers = DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.Volatile; private static readonly DeclarationModifiers s_methodModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_constructorModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_destructorModifiers = DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_propertyModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventFieldModifiers = DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_indexerModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_classModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_recordModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_structModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Ref | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_interfaceModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_accessorModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual; private static readonly DeclarationModifiers s_localFunctionModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static | DeclarationModifiers.Extern; private static readonly DeclarationModifiers s_lambdaModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static; private static DeclarationModifiers GetAllowedModifiers(SyntaxKind kind) { switch (kind) { case SyntaxKind.RecordDeclaration: return s_recordModifiers; case SyntaxKind.ClassDeclaration: return s_classModifiers; case SyntaxKind.EnumDeclaration: return DeclarationModifiers.New; case SyntaxKind.DelegateDeclaration: return DeclarationModifiers.New | DeclarationModifiers.Unsafe; case SyntaxKind.InterfaceDeclaration: return s_interfaceModifiers; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return s_structModifiers; case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return s_methodModifiers; case SyntaxKind.ConstructorDeclaration: return s_constructorModifiers; case SyntaxKind.DestructorDeclaration: return s_destructorModifiers; case SyntaxKind.FieldDeclaration: return s_fieldModifiers; case SyntaxKind.PropertyDeclaration: return s_propertyModifiers; case SyntaxKind.IndexerDeclaration: return s_indexerModifiers; case SyntaxKind.EventFieldDeclaration: return s_eventFieldModifiers; case SyntaxKind.EventDeclaration: return s_eventModifiers; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return s_accessorModifiers; case SyntaxKind.LocalFunctionStatement: return s_localFunctionModifiers; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return s_lambdaModifiers; case SyntaxKind.EnumMemberDeclaration: case SyntaxKind.Parameter: case SyntaxKind.LocalDeclarationStatement: default: return DeclarationModifiers.None; } } public override DeclarationModifiers GetModifiers(SyntaxNode declaration) { var modifierTokens = SyntaxFacts.GetModifierTokens(declaration); SyntaxFacts.GetAccessibilityAndModifiers(modifierTokens, out _, out var modifiers, out _); return modifiers; } public override SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers) => this.Isolate(declaration, d => this.WithModifiersInternal(d, modifiers)); private SyntaxNode WithModifiersInternal(SyntaxNode declaration, DeclarationModifiers modifiers) { modifiers &= GetAllowedModifiers(declaration.Kind()); var existingModifiers = this.GetModifiers(declaration); if (modifiers != existingModifiers) { return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out var accessibility, out var tmp, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } else { // no change return declaration; } } private static SyntaxNode SetModifierTokens(SyntaxNode declaration, SyntaxTokenList modifiers) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithModifiers(modifiers), ParameterSyntax parameter => parameter.WithModifiers(modifiers), LocalDeclarationStatementSyntax localDecl => localDecl.WithModifiers(modifiers), LocalFunctionStatementSyntax localFunc => localFunc.WithModifiers(modifiers), AccessorDeclarationSyntax accessor => accessor.WithModifiers(modifiers), AnonymousFunctionExpressionSyntax anonymous => anonymous.WithModifiers(modifiers), _ => declaration, }; private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers, SyntaxKind kind) => AsModifierList(accessibility, GetAllowedModifiers(kind) & modifiers); private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var list); switch (accessibility) { case Accessibility.Internal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.Public: list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Private: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.Protected: list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedOrInternal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedAndInternal: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.NotApplicable: break; } if (modifiers.IsAbstract) list.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); if (modifiers.IsNew) list.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); if (modifiers.IsSealed) list.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); if (modifiers.IsOverride) list.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); if (modifiers.IsVirtual) list.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); if (modifiers.IsStatic) list.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); if (modifiers.IsAsync) list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (modifiers.IsConst) list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); if (modifiers.IsReadOnly) list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); if (modifiers.IsUnsafe) list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); if (modifiers.IsVolatile) list.Add(SyntaxFactory.Token(SyntaxKind.VolatileKeyword)); if (modifiers.IsExtern) list.Add(SyntaxFactory.Token(SyntaxKind.ExternKeyword)); // partial and ref must be last if (modifiers.IsRef) list.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); if (modifiers.IsPartial) list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); return SyntaxFactory.TokenList(list); } private static TypeParameterListSyntax AsTypeParameterList(IEnumerable<string> typeParameterNames) { var typeParameters = typeParameterNames != null ? SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(name => SyntaxFactory.TypeParameter(name)))) : null; if (typeParameters != null && typeParameters.Parameters.Count == 0) { typeParameters = null; } return typeParameters; } public override SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNames) { var typeParameters = AsTypeParameterList(typeParameterNames); return declaration switch { MethodDeclarationSyntax method => method.WithTypeParameterList(typeParameters), TypeDeclarationSyntax type => type.WithTypeParameterList(typeParameters), DelegateDeclarationSyntax @delegate => @delegate.WithTypeParameterList(typeParameters), _ => declaration, }; } internal override SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations) => WithAccessibility(declaration switch { MethodDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), PropertyDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), EventDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), _ => declaration, }, Accessibility.NotApplicable); private static ExplicitInterfaceSpecifierSyntax CreateExplicitInterfaceSpecifier(ImmutableArray<ISymbol> explicitInterfaceImplementations) => SyntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceImplementations[0].ContainingType.GenerateNameSyntax()); public override SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) => declaration switch { MethodDeclarationSyntax method => method.WithConstraintClauses(WithTypeConstraints(method.ConstraintClauses, typeParameterName, kinds, types)), TypeDeclarationSyntax type => type.WithConstraintClauses(WithTypeConstraints(type.ConstraintClauses, typeParameterName, kinds, types)), DelegateDeclarationSyntax @delegate => @delegate.WithConstraintClauses(WithTypeConstraints(@delegate.ConstraintClauses, typeParameterName, kinds, types)), _ => declaration, }; private static SyntaxList<TypeParameterConstraintClauseSyntax> WithTypeConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> clauses, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) { var constraints = types != null ? SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(types.Select(t => SyntaxFactory.TypeConstraint((TypeSyntax)t))) : SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(); if ((kinds & SpecialTypeConstraintKind.Constructor) != 0) { constraints = constraints.Add(SyntaxFactory.ConstructorConstraint()); } var isReferenceType = (kinds & SpecialTypeConstraintKind.ReferenceType) != 0; var isValueType = (kinds & SpecialTypeConstraintKind.ValueType) != 0; if (isReferenceType || isValueType) { constraints = constraints.Insert(0, SyntaxFactory.ClassOrStructConstraint(isReferenceType ? SyntaxKind.ClassConstraint : SyntaxKind.StructConstraint)); } var clause = clauses.FirstOrDefault(c => c.Name.Identifier.ToString() == typeParameterName); if (clause == null) { if (constraints.Count > 0) { return clauses.Add(SyntaxFactory.TypeParameterConstraintClause(typeParameterName.ToIdentifierName(), constraints)); } else { return clauses; } } else if (constraints.Count == 0) { return clauses.Remove(clause); } else { return clauses.Replace(clause, clause.WithConstraints(constraints)); } } public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) => SyntaxFacts.GetDeclarationKind(declaration); public override string GetName(SyntaxNode declaration) => declaration switch { BaseTypeDeclarationSyntax baseTypeDeclaration => baseTypeDeclaration.Identifier.ValueText, DelegateDeclarationSyntax delegateDeclaration => delegateDeclaration.Identifier.ValueText, MethodDeclarationSyntax methodDeclaration => methodDeclaration.Identifier.ValueText, BaseFieldDeclarationSyntax baseFieldDeclaration => this.GetName(baseFieldDeclaration.Declaration), PropertyDeclarationSyntax propertyDeclaration => propertyDeclaration.Identifier.ValueText, EnumMemberDeclarationSyntax enumMemberDeclaration => enumMemberDeclaration.Identifier.ValueText, EventDeclarationSyntax eventDeclaration => eventDeclaration.Identifier.ValueText, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Name.ToString(), UsingDirectiveSyntax usingDirective => usingDirective.Name.ToString(), ParameterSyntax parameter => parameter.Identifier.ValueText, LocalDeclarationStatementSyntax localDeclaration => this.GetName(localDeclaration.Declaration), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => variableDeclaration.Variables[0].Identifier.ValueText, VariableDeclaratorSyntax variableDeclarator => variableDeclarator.Identifier.ValueText, TypeParameterSyntax typeParameter => typeParameter.Identifier.ValueText, AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => attributeList.Attributes[0].Name.ToString(), AttributeSyntax attribute => attribute.Name.ToString(), _ => string.Empty }; public override SyntaxNode WithName(SyntaxNode declaration, string name) => this.Isolate(declaration, d => this.WithNameInternal(d, name)); private SyntaxNode WithNameInternal(SyntaxNode declaration, string name) { var id = name.ToIdentifierToken(); return declaration switch { BaseTypeDeclarationSyntax typeDeclaration => ReplaceWithTrivia(declaration, typeDeclaration.Identifier, id), DelegateDeclarationSyntax delegateDeclaration => ReplaceWithTrivia(declaration, delegateDeclaration.Identifier, id), MethodDeclarationSyntax methodDeclaration => ReplaceWithTrivia(declaration, methodDeclaration.Identifier, id), BaseFieldDeclarationSyntax fieldDeclaration when fieldDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, fieldDeclaration.Declaration.Variables[0].Identifier, id), PropertyDeclarationSyntax propertyDeclaration => ReplaceWithTrivia(declaration, propertyDeclaration.Identifier, id), EnumMemberDeclarationSyntax enumMemberDeclaration => ReplaceWithTrivia(declaration, enumMemberDeclaration.Identifier, id), EventDeclarationSyntax eventDeclaration => ReplaceWithTrivia(declaration, eventDeclaration.Identifier, id), BaseNamespaceDeclarationSyntax namespaceDeclaration => ReplaceWithTrivia(declaration, namespaceDeclaration.Name, this.DottedName(name)), UsingDirectiveSyntax usingDeclaration => ReplaceWithTrivia(declaration, usingDeclaration.Name, this.DottedName(name)), ParameterSyntax parameter => ReplaceWithTrivia(declaration, parameter.Identifier, id), LocalDeclarationStatementSyntax localDeclaration when localDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, localDeclaration.Declaration.Variables[0].Identifier, id), TypeParameterSyntax typeParameter => ReplaceWithTrivia(declaration, typeParameter.Identifier, id), AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => ReplaceWithTrivia(declaration, attributeList.Attributes[0].Name, this.DottedName(name)), AttributeSyntax attribute => ReplaceWithTrivia(declaration, attribute.Name, this.DottedName(name)), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, variableDeclaration.Variables[0].Identifier, id), VariableDeclaratorSyntax variableDeclarator => ReplaceWithTrivia(declaration, variableDeclarator.Identifier, id), _ => declaration }; } public override SyntaxNode GetType(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return NotVoid(((DelegateDeclarationSyntax)declaration).ReturnType); case SyntaxKind.MethodDeclaration: return NotVoid(((MethodDeclarationSyntax)declaration).ReturnType); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).Type; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).Type; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).Type; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Type; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)declaration).Declaration.Type; case SyntaxKind.VariableDeclaration: return ((VariableDeclarationSyntax)declaration).Type; case SyntaxKind.VariableDeclarator: if (declaration.Parent != null) { return this.GetType(declaration.Parent); } break; } return null; } private static TypeSyntax NotVoid(TypeSyntax type) => type is PredefinedTypeSyntax pd && pd.Keyword.IsKind(SyntaxKind.VoidKeyword) ? null : type; public override SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type) => this.Isolate(declaration, d => WithTypeInternal(d, type)); private static SyntaxNode WithTypeInternal(SyntaxNode declaration, SyntaxNode type) => declaration.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(((FieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(((EventFieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.Parameter => ((ParameterSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(((LocalDeclarationStatementSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).WithType((TypeSyntax)type), _ => declaration, }; private SyntaxNode Isolate(SyntaxNode declaration, Func<SyntaxNode, SyntaxNode> editor) { var isolated = this.AsIsolatedDeclaration(declaration); return PreserveTrivia(isolated, editor); } private SyntaxNode AsIsolatedDeclaration(SyntaxNode declaration) { if (declaration != null) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Parent != null && vd.Variables.Count == 1) { return this.AsIsolatedDeclaration(vd.Parent); } break; case SyntaxKind.VariableDeclarator: var v = (VariableDeclaratorSyntax)declaration; if (v.Parent != null && v.Parent.Parent != null) { return this.ClearTrivia(WithVariable(v.Parent.Parent, v)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent != null) { var attrList = (AttributeListSyntax)attr.Parent; return attrList.WithAttributes(SyntaxFactory.SingletonSeparatedList(attr)).WithTarget(null); } break; } } return declaration; } private static SyntaxNode WithVariable(SyntaxNode declaration, VariableDeclaratorSyntax variable) { var vd = GetVariableDeclaration(declaration); if (vd != null) { return WithVariableDeclaration(declaration, vd.WithVariables(SyntaxFactory.SingletonSeparatedList(variable))); } return declaration; } private static VariableDeclarationSyntax GetVariableDeclaration(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration, _ => null, }; private static SyntaxNode WithVariableDeclaration(SyntaxNode declaration, VariableDeclarationSyntax variables) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(variables), _ => declaration, }; private static SyntaxNode GetFullDeclaration(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (CSharpSyntaxFacts.ParentIsFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsEventFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsLocalDeclarationStatement(vd)) { return vd.Parent; } else { return vd; } case SyntaxKind.VariableDeclarator: case SyntaxKind.Attribute: if (declaration.Parent != null) { return GetFullDeclaration(declaration.Parent); } break; } return declaration; } private SyntaxNode AsNodeLike(SyntaxNode existingNode, SyntaxNode newNode) { switch (this.GetDeclarationKind(existingNode)) { case DeclarationKind.Class: case DeclarationKind.Interface: case DeclarationKind.Struct: case DeclarationKind.Enum: case DeclarationKind.Namespace: case DeclarationKind.CompilationUnit: var container = this.GetDeclaration(existingNode.Parent); if (container != null) { return this.AsMemberOf(container, newNode); } break; case DeclarationKind.Attribute: return AsAttributeList(newNode); } return newNode; } public override IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration) { var list = declaration.GetParameterList(); return list != null ? list.Parameters : declaration is SimpleLambdaExpressionSyntax simpleLambda ? new[] { simpleLambda.Parameter } : SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters) { var newParameters = AsParameterList(parameters); var currentList = declaration.GetParameterList(); if (currentList == null) { currentList = declaration.IsKind(SyntaxKind.IndexerDeclaration) ? SyntaxFactory.BracketedParameterList() : (BaseParameterListSyntax)SyntaxFactory.ParameterList(); } var newList = currentList.WithParameters(currentList.Parameters.InsertRange(index, newParameters.Parameters)); return WithParameterList(declaration, newList); } public override IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement) { var statement = switchStatement as SwitchStatementSyntax; return statement?.Sections ?? SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections) { if (!(switchStatement is SwitchStatementSyntax statement)) { return switchStatement; } var newSections = statement.Sections.InsertRange(index, switchSections.Cast<SwitchSectionSyntax>()); return AddMissingTokens(statement, recurse: false).WithSections(newSections); } private static TNode AddMissingTokens<TNode>(TNode node, bool recurse) where TNode : CSharpSyntaxNode { var rewriter = new AddMissingTokensRewriter(recurse); return (TNode)rewriter.Visit(node); } private class AddMissingTokensRewriter : CSharpSyntaxRewriter { private readonly bool _recurse; private bool _firstVisit = true; public AddMissingTokensRewriter(bool recurse) => _recurse = recurse; public override SyntaxNode Visit(SyntaxNode node) { if (!_recurse && !_firstVisit) { return node; } _firstVisit = false; return base.Visit(node); } public override SyntaxToken VisitToken(SyntaxToken token) { var rewrittenToken = base.VisitToken(token); if (!rewrittenToken.IsMissing || !CSharp.SyntaxFacts.IsPunctuationOrKeyword(token.Kind())) { return rewrittenToken; } return SyntaxFactory.Token(token.Kind()).WithTriviaFrom(rewrittenToken); } } internal override SyntaxNode GetParameterListNode(SyntaxNode declaration) => declaration.GetParameterList(); private static SyntaxNode WithParameterList(SyntaxNode declaration, BaseParameterListSyntax list) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.SimpleLambdaExpression: var lambda = (SimpleLambdaExpressionSyntax)declaration; var parameters = list.Parameters; if (parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return lambda.WithParameter(parameters[0]); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), lambda.Body) .WithLeadingTrivia(lambda.GetLeadingTrivia()) .WithTrailingTrivia(lambda.GetTrailingTrivia()); } case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((RecordDeclarationSyntax)declaration).WithParameterList((ParameterListSyntax)list); default: return declaration; } } public override SyntaxNode GetExpression(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return pd.ExpressionBody.Expression; } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return id.ExpressionBody.Expression; } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return method.ExpressionBody.Expression; } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return local.ExpressionBody.Expression; } goto default; default: return GetEqualsValue(declaration)?.Value; } } public override SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression) => this.Isolate(declaration, d => WithExpressionInternal(d, expression)); private static SyntaxNode WithExpressionInternal(SyntaxNode declaration, SyntaxNode expression) { var expr = (ExpressionSyntax)expression; switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return ReplaceWithTrivia(pd, pd.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return ReplaceWithTrivia(id, id.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return ReplaceWithTrivia(method, method.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return ReplaceWithTrivia(local, local.ExpressionBody.Expression, expr); } goto default; default: var eq = GetEqualsValue(declaration); if (eq != null) { if (expression == null) { return WithEqualsValue(declaration, null); } else { // use replace so we only change the value part. return ReplaceWithTrivia(declaration, eq.Value, expr); } } else if (expression != null) { return WithEqualsValue(declaration, SyntaxFactory.EqualsValueClause(expr)); } else { return declaration; } } } private static EqualsValueClauseSyntax GetEqualsValue(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return fd.Declaration.Variables[0].Initializer; } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.Initializer; case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ld.Declaration.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return vd.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Initializer; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Default; } return null; } private static SyntaxNode WithEqualsValue(SyntaxNode declaration, EqualsValueClauseSyntax eq) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, fd.Declaration.Variables[0], fd.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.WithInitializer(eq); case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, ld.Declaration.Variables[0], ld.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return ReplaceWithTrivia(declaration, vd.Variables[0], vd.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).WithInitializer(eq); case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).WithDefault(eq); } return declaration; } private static readonly IReadOnlyList<SyntaxNode> s_EmptyList = SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); public override IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.AnonymousMethodExpression: return (((AnonymousMethodExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.ParenthesizedLambdaExpression: return (((ParenthesizedLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.SimpleLambdaExpression: return (((SimpleLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; default: return s_EmptyList; } } public override SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) { var body = CreateBlock(statements); var somebody = statements != null ? body : null; var semicolon = statements == null ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)declaration).WithBody(body); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); default: return declaration; } } public override IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration) { var list = GetAccessorList(declaration); return list?.Accessors ?? s_EmptyList; } public override SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors) { var newAccessors = AsAccessorList(accessors, declaration.Kind()); var currentList = GetAccessorList(declaration); if (currentList == null) { if (CanHaveAccessors(declaration)) { currentList = SyntaxFactory.AccessorList(); } else { return declaration; } } var newList = currentList.WithAccessors(currentList.Accessors.InsertRange(index, newAccessors.Accessors)); return WithAccessorList(declaration, newList); } internal static AccessorListSyntax GetAccessorList(SyntaxNode declaration) => (declaration as BasePropertyDeclarationSyntax)?.AccessorList; private static bool CanHaveAccessors(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.EventDeclaration => true, _ => false, }; private static SyntaxNode WithAccessorList(SyntaxNode declaration, AccessorListSyntax accessorList) => declaration switch { BasePropertyDeclarationSyntax baseProperty => baseProperty.WithAccessorList(accessorList), _ => declaration, }; private static AccessorListSyntax AsAccessorList(IEnumerable<SyntaxNode> nodes, SyntaxKind parentKind) { return SyntaxFactory.AccessorList( SyntaxFactory.List(nodes.Select(n => AsAccessor(n, parentKind)).Where(n => n != null))); } private static AccessorDeclarationSyntax AsAccessor(SyntaxNode node, SyntaxKind parentKind) { switch (parentKind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: switch (node.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; case SyntaxKind.EventDeclaration: switch (node.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; } return null; } private static AccessorDeclarationSyntax GetAccessor(SyntaxNode declaration, SyntaxKind kind) { var accessorList = GetAccessorList(declaration); return accessorList?.Accessors.FirstOrDefault(a => a.IsKind(kind)); } private SyntaxNode WithAccessor(SyntaxNode declaration, SyntaxKind kind, AccessorDeclarationSyntax accessor) => this.WithAccessor(declaration, GetAccessorList(declaration), kind, accessor); private SyntaxNode WithAccessor(SyntaxNode declaration, AccessorListSyntax accessorList, SyntaxKind kind, AccessorDeclarationSyntax accessor) { if (accessorList != null) { var acc = accessorList.Accessors.FirstOrDefault(a => a.IsKind(kind)); if (acc != null) { return this.ReplaceNode(declaration, acc, accessor); } else if (accessor != null) { return this.ReplaceNode(declaration, accessorList, accessorList.AddAccessors(accessor)); } } return declaration; } public override IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.GetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.SetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.GetAccessorDeclaration, statements); public override SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.SetAccessorDeclaration, statements); private SyntaxNode WithAccessorStatements(SyntaxNode declaration, SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var accessor = GetAccessor(declaration, kind); if (accessor == null) { accessor = AccessorDeclaration(kind, statements); return this.WithAccessor(declaration, kind, accessor); } else { return this.WithAccessor(declaration, kind, (AccessorDeclarationSyntax)this.WithStatements(accessor, statements)); } } public override IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration) { var baseList = GetBaseList(declaration); if (baseList != null) { return baseList.Types.OfType<SimpleBaseTypeSyntax>().Select(bt => bt.Type).ToReadOnlyCollection(); } else { return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } } public override SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(0, SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } } public override SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(baseList.Types.Count, SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } } private static SyntaxNode AddBaseList(SyntaxNode declaration, BaseListSyntax baseList) { var newDecl = WithBaseList(declaration, baseList); // move trivia from type identifier to after base list return ShiftTrivia(newDecl, GetBaseList(newDecl)); } private static BaseListSyntax GetBaseList(SyntaxNode declaration) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.BaseList : null; private static SyntaxNode WithBaseList(SyntaxNode declaration, BaseListSyntax baseList) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.WithBaseList(baseList) : declaration; #endregion #region Remove, Replace, Insert public override SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode declaration, SyntaxNode newDeclaration) { newDeclaration = this.AsNodeLike(declaration, newDeclaration); if (newDeclaration == null) { return this.RemoveNode(root, declaration); } if (root.Span.Contains(declaration.Span)) { var newFullDecl = this.AsIsolatedDeclaration(newDeclaration); var fullDecl = GetFullDeclaration(declaration); // special handling for replacing at location of sub-declaration if (fullDecl != declaration && fullDecl.IsKind(newFullDecl.Kind())) { // try to replace inline if possible if (GetDeclarationCount(newFullDecl) == 1) { var newSubDecl = GetSubDeclarations(newFullDecl)[0]; if (AreInlineReplaceableSubDeclarations(declaration, newSubDecl)) { return base.ReplaceNode(root, declaration, newSubDecl); } } // replace sub declaration by splitting full declaration and inserting between var index = this.IndexOf(GetSubDeclarations(fullDecl), declaration); // replace declaration with multiple declarations return ReplaceRange(root, fullDecl, this.SplitAndReplace(fullDecl, index, new[] { newDeclaration })); } // attempt normal replace return base.ReplaceNode(root, declaration, newFullDecl); } else { return base.ReplaceNode(root, declaration, newDeclaration); } } // returns true if one sub-declaration can be replaced inline with another sub-declaration private static bool AreInlineReplaceableSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.Attribute: case SyntaxKind.VariableDeclarator: return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent); } } return false; } private static bool AreSimilarExceptForSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { if (decl1 == decl2) { return true; } if (decl1 == null || decl2 == null) { return false; } var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.FieldDeclaration: var fd1 = (FieldDeclarationSyntax)decl1; var fd2 = (FieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) && SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists); case SyntaxKind.EventFieldDeclaration: var efd1 = (EventFieldDeclarationSyntax)decl1; var efd2 = (EventFieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(efd1.Modifiers, efd2.Modifiers) && SyntaxFactory.AreEquivalent(efd1.AttributeLists, efd2.AttributeLists); case SyntaxKind.LocalDeclarationStatement: var ld1 = (LocalDeclarationStatementSyntax)decl1; var ld2 = (LocalDeclarationStatementSyntax)decl2; return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers); case SyntaxKind.AttributeList: // don't compare targets, since aren't part of the abstraction return true; case SyntaxKind.VariableDeclaration: var vd1 = (VariableDeclarationSyntax)decl1; var vd2 = (VariableDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(vd1.Type, vd2.Type) && AreSimilarExceptForSubDeclarations(vd1.Parent, vd2.Parent); } } return false; } // replaces sub-declaration by splitting multi-part declaration first private IEnumerable<SyntaxNode> SplitAndReplace(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); if (index >= 0 && index < count) { var newNodes = new List<SyntaxNode>(); if (index > 0) { // make a single declaration with only sub-declarations before the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } newNodes.AddRange(newDeclarations); if (index < count - 1) { // make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); } return newNodes; } else { return newDeclarations; } } public override SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesBefore(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesBeforeInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesBefore(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index > 0) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index, newDeclarations)); } return base.InsertNodesBefore(root, fullDecl, newDeclarations); } public override SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesAfter(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesAfterInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesAfter(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var count = subDecls.Count; var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index >= 0 && index < count - 1) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index + 1, newDeclarations)); } return base.InsertNodesAfter(root, fullDecl, newDeclarations); } private IEnumerable<SyntaxNode> SplitAndInsert(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); var newNodes = new List<SyntaxNode>(); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); newNodes.AddRange(newDeclarations); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); return newNodes; } private SyntaxNode WithSubDeclarationsRemoved(SyntaxNode declaration, int index, int count) => this.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)); private static IReadOnlyList<SyntaxNode> GetSubDeclarations(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => this.RemoveNode(root, node, DefaultRemoveOptions); public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) { if (node.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Remove the entire global statement as part of the edit node = node.Parent; } if (root.Span.Contains(node.Span)) { // node exists within normal span of the root (not in trivia) return this.Isolate(root.TrackNodes(node), r => this.RemoveNodeInternal(r, r.GetCurrentNode(node), options)); } else { return this.RemoveNodeInternal(root, node, options); } } private SyntaxNode RemoveNodeInternal(SyntaxNode root, SyntaxNode declaration, SyntaxRemoveOptions options) { switch (declaration.Kind()) { case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent is AttributeListSyntax attrList && attrList.Attributes.Count == 1) { // remove entire list if only one attribute return this.RemoveNodeInternal(root, attrList, options); } break; case SyntaxKind.AttributeArgument: if (declaration.Parent != null && ((AttributeArgumentListSyntax)declaration.Parent).Arguments.Count == 1) { // remove entire argument list if only one argument return this.RemoveNodeInternal(root, declaration.Parent, options); } break; case SyntaxKind.VariableDeclarator: var full = GetFullDeclaration(declaration); if (full != declaration && GetDeclarationCount(full) == 1) { // remove full declaration if only one declarator return this.RemoveNodeInternal(root, full, options); } break; case SyntaxKind.SimpleBaseType: if (declaration.Parent is BaseListSyntax baseList && baseList.Types.Count == 1) { // remove entire base list if this is the only base type. return this.RemoveNodeInternal(root, baseList, options); } break; default: var parent = declaration.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.SimpleBaseType: return this.RemoveNodeInternal(root, parent, options); } } break; } return base.RemoveNode(root, declaration, options); } /// <summary> /// Moves the trailing trivia from the node's previous token to the end of the node /// </summary> private static SyntaxNode ShiftTrivia(SyntaxNode root, SyntaxNode node) { var firstToken = node.GetFirstToken(); var previousToken = firstToken.GetPreviousToken(); if (previousToken != default && root.Contains(previousToken.Parent)) { var newNode = node.WithTrailingTrivia(node.GetTrailingTrivia().AddRange(previousToken.TrailingTrivia)); var newPreviousToken = previousToken.WithTrailingTrivia(default(SyntaxTriviaList)); return root.ReplaceSyntax( nodes: new[] { node }, computeReplacementNode: (o, r) => newNode, tokens: new[] { previousToken }, computeReplacementToken: (o, r) => newPreviousToken, trivia: null, computeReplacementTrivia: null); } return root; } internal override bool IsRegularOrDocComment(SyntaxTrivia trivia) => trivia.IsRegularOrDocComment(); #endregion #region Statements and Expressions public override SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode AwaitExpression(SyntaxNode expression) => SyntaxFactory.AwaitExpression((ExpressionSyntax)expression); public override SyntaxNode NameOfExpression(SyntaxNode expression) => this.InvocationExpression(s_nameOfIdentifier, expression); public override SyntaxNode ReturnStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ReturnStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ThrowStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowExpression(SyntaxNode expression) => SyntaxFactory.ThrowExpression((ExpressionSyntax)expression); internal override bool SupportsThrowExpression() => true; public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null) { if (falseStatements == null) { return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements)); } else { var falseArray = falseStatements.ToList(); // make else-if chain if false-statements contain only an if-statement return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements), SyntaxFactory.ElseClause( falseArray.Count == 1 && falseArray[0] is IfStatementSyntax ? (StatementSyntax)falseArray[0] : CreateBlock(falseArray))); } } private static BlockSyntax CreateBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(AsStatementList(statements)).WithAdditionalAnnotations(Simplifier.Annotation); private static SyntaxList<StatementSyntax> AsStatementList(IEnumerable<SyntaxNode> nodes) => nodes == null ? default : SyntaxFactory.List(nodes.Select(AsStatement)); private static StatementSyntax AsStatement(SyntaxNode node) { if (node is ExpressionSyntax expression) { return SyntaxFactory.ExpressionStatement(expression); } return (StatementSyntax)node; } public override SyntaxNode ExpressionStatement(SyntaxNode expression) => SyntaxFactory.ExpressionStatement((ExpressionSyntax)expression); internal override SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode simpleName) { return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParenthesizeLeft((ExpressionSyntax)expression), (SimpleNameSyntax)simpleName); } public override SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull) => SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull); public override SyntaxNode MemberBindingExpression(SyntaxNode name) => SyntaxGeneratorInternal.MemberBindingExpression(name); public override SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementBindingExpression( SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments))); /// <summary> /// Parenthesize the left hand size of a member access, invocation or element access expression /// </summary> private static ExpressionSyntax ParenthesizeLeft(ExpressionSyntax expression) { if (expression is TypeSyntax || expression.IsKind(SyntaxKind.ThisExpression) || expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.ParenthesizedExpression) || expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || expression.IsKind(SyntaxKind.InvocationExpression) || expression.IsKind(SyntaxKind.ElementAccessExpression) || expression.IsKind(SyntaxKind.MemberBindingExpression)) { return expression; } return (ExpressionSyntax)Parenthesize(expression); } private static SeparatedSyntaxList<ExpressionSyntax> AsExpressionList(IEnumerable<SyntaxNode> expressions) => SyntaxFactory.SeparatedList(expressions.OfType<ExpressionSyntax>()); public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)size)))); return SyntaxFactory.ArrayCreationExpression(arrayType); } public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression())))); var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, AsExpressionList(elements)); return SyntaxFactory.ArrayCreationExpression(arrayType, initializer); } public override SyntaxNode ObjectCreationExpression(SyntaxNode type, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ObjectCreationExpression((TypeSyntax)type, CreateArgumentList(arguments), null); internal override SyntaxNode ObjectCreationExpression(SyntaxNode type, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen) => SyntaxFactory.ObjectCreationExpression( (TypeSyntax)type, SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer: null); private static ArgumentListSyntax CreateArgumentList(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(CreateArguments(arguments)); private static SeparatedSyntaxList<ArgumentSyntax> CreateArguments(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.SeparatedList(arguments.Select(AsArgument)); private static ArgumentSyntax AsArgument(SyntaxNode argOrExpression) => argOrExpression as ArgumentSyntax ?? SyntaxFactory.Argument((ExpressionSyntax)argOrExpression); public override SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.InvocationExpression(ParenthesizeLeft((ExpressionSyntax)expression), CreateArgumentList(arguments)); public override SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementAccessExpression(ParenthesizeLeft((ExpressionSyntax)expression), SyntaxFactory.BracketedArgumentList(CreateArguments(arguments))); internal override SyntaxToken NumericLiteralToken(string text, ulong value) => SyntaxFactory.Literal(text, value); public override SyntaxNode DefaultExpression(SyntaxNode type) => SyntaxFactory.DefaultExpression((TypeSyntax)type).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode DefaultExpression(ITypeSymbol type) { // If it's just a reference type, then "null" is the default expression for it. Note: // this counts for actual reference type, or a type parameter with a 'class' constraint. // Also, if it's a nullable type, then we can use "null". if (type.IsReferenceType || type.IsPointerType() || type.IsNullable()) { return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); } switch (type.SpecialType) { case SpecialType.System_Boolean: return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0)); } // Default to a "default(<typename>)" expression. return DefaultExpression(type.GenerateTypeSyntax()); } private static SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => CSharpSyntaxGeneratorInternal.Parenthesize(expression, includeElasticTrivia, addSimplifierAnnotation); public override SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.IsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode TypeOfExpression(SyntaxNode type) => SyntaxFactory.TypeOfExpression((TypeSyntax)type); public override SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)left, (ExpressionSyntax)Parenthesize(right)); private static SyntaxNode CreateBinaryExpression(SyntaxKind syntaxKind, SyntaxNode left, SyntaxNode right) => SyntaxFactory.BinaryExpression(syntaxKind, (ExpressionSyntax)Parenthesize(left), (ExpressionSyntax)Parenthesize(right)); public override SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanExpression, left, right); public override SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); public override SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanExpression, left, right); public override SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); public override SyntaxNode NegateExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.AddExpression, left, right); public override SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.SubtractExpression, left, right); public override SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.MultiplyExpression, left, right); public override SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.DivideExpression, left, right); public override SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.ModuloExpression, left, right); public override SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); public override SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); public override SyntaxNode BitwiseNotExpression(SyntaxNode operand) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, (ExpressionSyntax)Parenthesize(operand)); public override SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalAndExpression, left, right); public override SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalOrExpression, left, right); public override SyntaxNode LogicalNotExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse) => SyntaxFactory.ConditionalExpression((ExpressionSyntax)Parenthesize(condition), (ExpressionSyntax)Parenthesize(whenTrue), (ExpressionSyntax)Parenthesize(whenFalse)); public override SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.CoalesceExpression, left, right); public override SyntaxNode ThisExpression() => SyntaxFactory.ThisExpression(); public override SyntaxNode BaseExpression() => SyntaxFactory.BaseExpression(); public override SyntaxNode LiteralExpression(object value) => ExpressionGenerator.GenerateNonEnumValueExpression(null, value, canUseFieldReference: true); public override SyntaxNode TypedConstantExpression(TypedConstant value) => ExpressionGenerator.GenerateExpression(value); public override SyntaxNode IdentifierName(string identifier) => identifier.ToIdentifierName(); public override SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments) => GenericName(identifier.ToIdentifierToken(), typeArguments); internal override SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments) => SyntaxFactory.GenericName(identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); public override SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments) { switch (expression.Kind()) { case SyntaxKind.IdentifierName: var sname = (SimpleNameSyntax)expression; return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.GenericName: var gname = (GenericNameSyntax)expression; return gname.WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.QualifiedName: var qname = (QualifiedNameSyntax)expression; return qname.WithRight((SimpleNameSyntax)this.WithTypeArguments(qname.Right, typeArguments)); case SyntaxKind.AliasQualifiedName: var aname = (AliasQualifiedNameSyntax)expression; return aname.WithName((SimpleNameSyntax)this.WithTypeArguments(aname.Name, typeArguments)); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var sma = (MemberAccessExpressionSyntax)expression; return sma.WithName((SimpleNameSyntax)this.WithTypeArguments(sma.Name, typeArguments)); default: return expression; } } public override SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right) => SyntaxFactory.QualifiedName((NameSyntax)left, (SimpleNameSyntax)right).WithAdditionalAnnotations(Simplifier.Annotation); internal override SyntaxNode GlobalAliasedName(SyntaxNode name) => SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)name); public override SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol) => namespaceOrTypeSymbol.GenerateNameSyntax(); public override SyntaxNode TypeExpression(ITypeSymbol typeSymbol) => typeSymbol.GenerateTypeSyntax(); public override SyntaxNode TypeExpression(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)), SpecialType.System_Byte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)), SpecialType.System_Char => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)), SpecialType.System_Decimal => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)), SpecialType.System_Double => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)), SpecialType.System_Int16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)), SpecialType.System_Int32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)), SpecialType.System_Int64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)), SpecialType.System_Object => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), SpecialType.System_SByte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)), SpecialType.System_Single => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.FloatKeyword)), SpecialType.System_String => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SpecialType.System_UInt16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)), SpecialType.System_UInt32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntKeyword)), SpecialType.System_UInt64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)), _ => throw new NotSupportedException("Unsupported SpecialType"), }; public override SyntaxNode ArrayTypeExpression(SyntaxNode type) => SyntaxFactory.ArrayType((TypeSyntax)type, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())); public override SyntaxNode NullableTypeExpression(SyntaxNode type) { if (type is NullableTypeSyntax) { return type; } else { return SyntaxFactory.NullableType((TypeSyntax)type); } } internal override SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements) => SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast<TupleElementSyntax>())); public override SyntaxNode TupleElementExpression(SyntaxNode type, string name = null) => SyntaxFactory.TupleElement((TypeSyntax)type, name?.ToIdentifierToken() ?? default); public override SyntaxNode Argument(string nameOpt, RefKind refKind, SyntaxNode expression) { return SyntaxFactory.Argument( nameOpt == null ? null : SyntaxFactory.NameColon(nameOpt), GetArgumentModifiers(refKind), (ExpressionSyntax)expression); } public override SyntaxNode LocalDeclarationStatement(SyntaxNode type, string name, SyntaxNode initializer, bool isConst) => CSharpSyntaxGeneratorInternal.Instance.LocalDeclarationStatement(type, name.ToIdentifierToken(), initializer, isConst); public override SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( CSharpSyntaxGeneratorInternal.VariableDeclaration(type, name.ToIdentifierToken(), expression), expression: null, statement: CreateBlock(statements)); } public override SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( declaration: null, expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.LockStatement( expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null) { return SyntaxFactory.TryStatement( CreateBlock(tryStatements), catchClauses != null ? SyntaxFactory.List(catchClauses.Cast<CatchClauseSyntax>()) : default, finallyStatements != null ? SyntaxFactory.FinallyClause(CreateBlock(finallyStatements)) : null); } public override SyntaxNode CatchClause(SyntaxNode type, string name, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.CatchClause( SyntaxFactory.CatchDeclaration((TypeSyntax)type, name.ToIdentifierToken()), filter: null, block: CreateBlock(statements)); } public override SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements) => SyntaxFactory.WhileStatement((ExpressionSyntax)condition, CreateBlock(statements)); public override SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> caseClauses) { if (expression is TupleExpressionSyntax) { return SyntaxFactory.SwitchStatement( (ExpressionSyntax)expression, caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList()); } else { return SyntaxFactory.SwitchStatement( SyntaxFactory.Token(SyntaxKind.SwitchKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), (ExpressionSyntax)expression, SyntaxFactory.Token(SyntaxKind.CloseParenToken), SyntaxFactory.Token(SyntaxKind.OpenBraceToken), caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList(), SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } } public override SyntaxNode SwitchSection(IEnumerable<SyntaxNode> expressions, IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(AsSwitchLabels(expressions), AsStatementList(statements)); internal override SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.SwitchSection( labels.Cast<SwitchLabelSyntax>().ToSyntaxList(), AsStatementList(statements)); } public override SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(SyntaxFactory.SingletonList(SyntaxFactory.DefaultSwitchLabel() as SwitchLabelSyntax), AsStatementList(statements)); private static SyntaxList<SwitchLabelSyntax> AsSwitchLabels(IEnumerable<SyntaxNode> expressions) { var labels = default(SyntaxList<SwitchLabelSyntax>); if (expressions != null) { labels = labels.AddRange(expressions.Select(e => SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)e))); } return labels; } public override SyntaxNode ExitSwitchStatement() => SyntaxFactory.BreakStatement(); internal override SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(statements.Cast<StatementSyntax>()); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, SyntaxNode expression) { var parameters = parameterDeclarations?.Cast<ParameterSyntax>().ToList(); if (parameters != null && parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return SyntaxFactory.SimpleLambdaExpression(parameters[0], (CSharpSyntaxNode)expression); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), (CSharpSyntaxNode)expression); } } private static bool IsSimpleLambdaParameter(SyntaxNode node) => node is ParameterSyntax p && p.Type == null && p.Default == null && p.Modifiers.Count == 0; public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression) => this.ValueReturningLambdaExpression(lambdaParameters, expression); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(parameterDeclarations, CreateBlock(statements)); public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(lambdaParameters, statements); public override SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null) => this.ParameterDeclaration(identifier, type, null, RefKind.None); internal override SyntaxNode IdentifierName(SyntaxToken identifier) => SyntaxFactory.IdentifierName(identifier); internal override SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression) { return SyntaxFactory.AnonymousObjectMemberDeclarator( SyntaxFactory.NameEquals((IdentifierNameSyntax)identifier), (ExpressionSyntax)expression); } public override SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AsArgument))); internal override SyntaxNode RemoveAllComments(SyntaxNode node) { var modifiedNode = RemoveLeadingAndTrailingComments(node); if (modifiedNode is TypeDeclarationSyntax declarationSyntax) { return declarationSyntax.WithOpenBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.OpenBraceToken)) .WithCloseBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.CloseBraceToken)); } return modifiedNode; } internal override SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList) { static IEnumerable<IEnumerable<SyntaxTrivia>> splitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } var syntaxWithoutComments = splitIntoLines(syntaxTriviaList) .Where(trivia => !trivia.Any(t => t.IsRegularOrDocComment())) .SelectMany(t => t); return new SyntaxTriviaList(syntaxWithoutComments); } internal override SyntaxNode ParseExpression(string stringToParse) => SyntaxFactory.ParseExpression(stringToParse); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageService(typeof(SyntaxGenerator), LanguageNames.CSharp), Shared] internal class CSharpSyntaxGenerator : SyntaxGenerator { // A bit hacky, but we need to actually run ParseToken on the "nameof" text as there's no // other way to get a token back that has the appropriate internal bit set that indicates // this has the .ContextualKind of SyntaxKind.NameOfKeyword. private static readonly IdentifierNameSyntax s_nameOfIdentifier = SyntaxFactory.IdentifierName(SyntaxFactory.ParseToken("nameof")); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpSyntaxGenerator() { } internal override SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; internal override SyntaxTrivia CarriageReturnLineFeed => SyntaxFactory.CarriageReturnLineFeed; internal override bool RequiresExplicitImplementationForInterfaceMembers => false; internal override SyntaxGeneratorInternal SyntaxGeneratorInternal => CSharpSyntaxGeneratorInternal.Instance; internal override SyntaxTrivia Whitespace(string text) => SyntaxFactory.Whitespace(text); internal override SyntaxTrivia SingleLineComment(string text) => SyntaxFactory.Comment("//" + text); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) => SyntaxFactory.SeparatedList<TElement>(list); internal override SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim) { const string InterpolatedVerbatimText = "$@\""; return isVerbatim ? SyntaxFactory.Token(default, SyntaxKind.InterpolatedVerbatimStringStartToken, InterpolatedVerbatimText, InterpolatedVerbatimText, default) : SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken); } internal override SyntaxToken CreateInterpolatedStringEndToken() => SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) => SyntaxFactory.SeparatedList(nodes, separators); internal override SyntaxTrivia Trivia(SyntaxNode node) { if (node is StructuredTriviaSyntax structuredTriviaSyntax) { return SyntaxFactory.Trivia(structuredTriviaSyntax); } throw ExceptionUtilities.UnexpectedValue(node.Kind()); } internal override SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString) { var docTrivia = SyntaxFactory.DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, SyntaxFactory.List(nodes), SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken)); docTrivia = docTrivia.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/// ")) .WithTrailingTrivia(trailingTrivia); if (lastWhitespaceTrivia == default) return docTrivia.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)); return docTrivia.WithTrailingTrivia( SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia); } internal override SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return SyntaxFactory.DocumentationCommentTrivia(documentationCommentTrivia.Kind(), SyntaxFactory.List(content), documentationCommentTrivia.EndOfComment); } return null; } public static readonly SyntaxGenerator Instance = new CSharpSyntaxGenerator(); #region Declarations public override SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.CompilationUnit() .WithUsings(this.AsUsingDirectives(declarations)) .WithMembers(AsNamespaceMembers(declarations)); } private SyntaxList<UsingDirectiveSyntax> AsUsingDirectives(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(this.AsUsingDirective).OfType<UsingDirectiveSyntax>()) : default; } private SyntaxNode AsUsingDirective(SyntaxNode node) { if (node is NameSyntax name) { return this.NamespaceImportDeclaration(name); } return node as UsingDirectiveSyntax; } private static SyntaxList<MemberDeclarationSyntax> AsNamespaceMembers(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(AsNamespaceMember).OfType<MemberDeclarationSyntax>()) : default; } private static SyntaxNode AsNamespaceMember(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return declaration; default: return null; } } public override SyntaxNode NamespaceImportDeclaration(SyntaxNode name) => SyntaxFactory.UsingDirective((NameSyntax)name); public override SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name) => SyntaxFactory.UsingDirective(SyntaxFactory.NameEquals(aliasIdentifierName), (NameSyntax)name); public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.NamespaceDeclaration( (NameSyntax)name, default, this.AsUsingDirectives(declarations), AsNamespaceMembers(declarations)); } public override SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode initializer) { return SyntaxFactory.FieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.FieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( name.ToIdentifierToken(), null, initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null)))); } public override SyntaxNode ParameterDeclaration(string name, SyntaxNode type, SyntaxNode initializer, RefKind refKind) { return SyntaxFactory.Parameter( default, CSharpSyntaxGeneratorInternal.GetParameterModifiers(refKind), (TypeSyntax)type, name.ToIdentifierToken(), initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null); } internal static SyntaxToken GetArgumentModifiers(RefKind refKind) { switch (refKind) { case RefKind.None: case RefKind.In: return default; case RefKind.Out: return SyntaxFactory.Token(SyntaxKind.OutKeyword); case RefKind.Ref: return SyntaxFactory.Token(SyntaxKind.RefKeyword); default: throw ExceptionUtilities.UnexpectedValue(refKind); } } public override SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> statements) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); return SyntaxFactory.MethodDeclaration( attributeLists: default, modifiers: AsModifierList(accessibility, modifiers, SyntaxKind.MethodDeclaration), returnType: returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), explicitInterfaceSpecifier: null, identifier: name.ToIdentifierToken(), typeParameterList: AsTypeParameterList(typeParameters), parameterList: AsParameterList(parameters), constraintClauses: default, body: hasBody ? CreateBlock(statements) : null, expressionBody: null, semicolonToken: !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); } public override SyntaxNode OperatorDeclaration(OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); var returnTypeNode = returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); var parameterList = AsParameterList(parameters); var body = hasBody ? CreateBlock(statements) : null; var semicolon = !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; var modifierList = AsModifierList(accessibility, modifiers, SyntaxKind.OperatorDeclaration); var attributes = default(SyntaxList<AttributeListSyntax>); if (kind == OperatorKind.ImplicitConversion || kind == OperatorKind.ExplicitConversion) { return SyntaxFactory.ConversionOperatorDeclaration( attributes, modifierList, SyntaxFactory.Token(GetTokenKind(kind)), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), returnTypeNode, parameterList, body, semicolon); } else { return SyntaxFactory.OperatorDeclaration( attributes, modifierList, returnTypeNode, SyntaxFactory.Token(SyntaxKind.OperatorKeyword), SyntaxFactory.Token(GetTokenKind(kind)), parameterList, body, semicolon); } } private static SyntaxKind GetTokenKind(OperatorKind kind) => kind switch { OperatorKind.ImplicitConversion => SyntaxKind.ImplicitKeyword, OperatorKind.ExplicitConversion => SyntaxKind.ExplicitKeyword, OperatorKind.Addition => SyntaxKind.PlusToken, OperatorKind.BitwiseAnd => SyntaxKind.AmpersandToken, OperatorKind.BitwiseOr => SyntaxKind.BarToken, OperatorKind.Decrement => SyntaxKind.MinusMinusToken, OperatorKind.Division => SyntaxKind.SlashToken, OperatorKind.Equality => SyntaxKind.EqualsEqualsToken, OperatorKind.ExclusiveOr => SyntaxKind.CaretToken, OperatorKind.False => SyntaxKind.FalseKeyword, OperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, OperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, OperatorKind.Increment => SyntaxKind.PlusPlusToken, OperatorKind.Inequality => SyntaxKind.ExclamationEqualsToken, OperatorKind.LeftShift => SyntaxKind.LessThanLessThanToken, OperatorKind.LessThan => SyntaxKind.LessThanToken, OperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, OperatorKind.LogicalNot => SyntaxKind.ExclamationToken, OperatorKind.Modulus => SyntaxKind.PercentToken, OperatorKind.Multiply => SyntaxKind.AsteriskToken, OperatorKind.OnesComplement => SyntaxKind.TildeToken, OperatorKind.RightShift => SyntaxKind.GreaterThanGreaterThanToken, OperatorKind.Subtraction => SyntaxKind.MinusToken, OperatorKind.True => SyntaxKind.TrueKeyword, OperatorKind.UnaryNegation => SyntaxKind.MinusToken, OperatorKind.UnaryPlus => SyntaxKind.PlusToken, _ => throw new ArgumentException("Unknown operator kind."), }; private static ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.ParameterList(); } public override SyntaxNode ConstructorDeclaration( string name, IEnumerable<SyntaxNode> parameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> baseConstructorArguments, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.ConstructorDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ConstructorDeclaration), (name ?? "ctor").ToIdentifierToken(), AsParameterList(parameters), baseConstructorArguments != null ? SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(baseConstructorArguments.Select(AsArgument)))) : null, CreateBlock(statements)); } public override SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } if (hasGetter) accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); if (hasSetter) accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.PropertyDeclaration( attributeLists: default, AsModifierList(accessibility, actualModifiers, SyntaxKind.PropertyDeclaration), (TypeSyntax)type, explicitInterfaceSpecifier: null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode GetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, accessibility, statements); public override SyntaxNode SetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, accessibility, statements); private static SyntaxNode AccessorDeclaration( SyntaxKind kind, Accessibility accessibility, IEnumerable<SyntaxNode> statements) { var accessor = SyntaxFactory.AccessorDeclaration(kind); accessor = accessor.WithModifiers( AsModifierList(accessibility, DeclarationModifiers.None, SyntaxKind.PropertyDeclaration)); accessor = statements == null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) : accessor.WithBody(CreateBlock(statements)); return accessor; } public override SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations) => declaration switch { PropertyDeclarationSyntax property => property.WithAccessorList(CreateAccessorList(property.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), IndexerDeclarationSyntax indexer => indexer.WithAccessorList(CreateAccessorList(indexer.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), _ => declaration, }; private static AccessorListSyntax CreateAccessorList(AccessorListSyntax accessorListOpt, IEnumerable<SyntaxNode> accessorDeclarations) { var list = SyntaxFactory.List(accessorDeclarations.Cast<AccessorDeclarationSyntax>()); return accessorListOpt == null ? SyntaxFactory.AccessorList(list) : accessorListOpt.WithAccessors(list); } public override SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } else { if (getAccessorStatements == null && hasGetter) { getAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (setAccessorStatements == null && hasSetter) { setAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } if (hasGetter) { accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); } if (hasSetter) { accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); } var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.IndexerDeclaration( default, AsModifierList(accessibility, actualModifiers, SyntaxKind.IndexerDeclaration), (TypeSyntax)type, null, AsBracketedParameterList(parameters), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } private static BracketedParameterListSyntax AsBracketedParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.BracketedParameterList(); } private static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var ad = SyntaxFactory.AccessorDeclaration( kind, statements != null ? CreateBlock(statements) : null); if (statements == null) { ad = ad.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return ad; } public override SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers) { return SyntaxFactory.EventFieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventFieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(name)))); } public override SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> parameters, IEnumerable<SyntaxNode> addAccessorStatements, IEnumerable<SyntaxNode> removeAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); if (modifiers.IsAbstract) { addAccessorStatements = null; removeAccessorStatements = null; } else { if (addAccessorStatements == null) { addAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (removeAccessorStatements == null) { removeAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } accessors.Add(AccessorDeclaration(SyntaxKind.AddAccessorDeclaration, addAccessorStatements)); accessors.Add(AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration, removeAccessorStatements)); return SyntaxFactory.EventDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventDeclaration), (TypeSyntax)type, null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { // C# interface implementations are implicit/not-specified -- so they are just named the name as the interface member return PreserveTrivia(declaration, d => { d = WithInterfaceSpecifier(d, null); d = this.AsImplementation(d, Accessibility.Public); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return d; }); } public override SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { return PreserveTrivia(declaration, d => { d = this.AsImplementation(d, Accessibility.NotApplicable); d = this.WithoutConstraints(d); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return WithInterfaceSpecifier(d, SyntaxFactory.ExplicitInterfaceSpecifier((NameSyntax)interfaceTypeName)); }); } private SyntaxNode WithoutConstraints(SyntaxNode declaration) { if (declaration.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax method)) { if (method.ConstraintClauses.Count > 0) { return this.RemoveNodes(method, method.ConstraintClauses); } } return declaration; } private static SyntaxNode WithInterfaceSpecifier(SyntaxNode declaration, ExplicitInterfaceSpecifierSyntax specifier) => declaration.Kind() switch { SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), _ => declaration, }; private SyntaxNode AsImplementation(SyntaxNode declaration, Accessibility requiredAccess) { declaration = this.WithAccessibility(declaration, requiredAccess); declaration = this.WithModifiers(declaration, this.GetModifiers(declaration) - DeclarationModifiers.Abstract); declaration = WithBodies(declaration); return declaration; } private static SyntaxNode WithBodies(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; return method.Body == null ? method.WithSemicolonToken(default).WithBody(CreateBlock(null)) : method; case SyntaxKind.OperatorDeclaration: var op = (OperatorDeclarationSyntax)declaration; return op.Body == null ? op.WithSemicolonToken(default).WithBody(CreateBlock(null)) : op; case SyntaxKind.ConversionOperatorDeclaration: var cop = (ConversionOperatorDeclarationSyntax)declaration; return cop.Body == null ? cop.WithSemicolonToken(default).WithBody(CreateBlock(null)) : cop; case SyntaxKind.PropertyDeclaration: var prop = (PropertyDeclarationSyntax)declaration; return prop.WithAccessorList(WithBodies(prop.AccessorList)); case SyntaxKind.IndexerDeclaration: var ind = (IndexerDeclarationSyntax)declaration; return ind.WithAccessorList(WithBodies(ind.AccessorList)); case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)declaration; return ev.WithAccessorList(WithBodies(ev.AccessorList)); } return declaration; } private static AccessorListSyntax WithBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(x => WithBody(x)))); private static AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax accessor) { if (accessor.Body == null) { return accessor.WithSemicolonToken(default).WithBody(CreateBlock(null)); } else { return accessor; } } private static AccessorListSyntax WithoutBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(WithoutBody))); private static AccessorDeclarationSyntax WithoutBody(AccessorDeclarationSyntax accessor) => accessor.Body != null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithBody(null) : accessor; public override SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode baseType, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { List<BaseTypeSyntax> baseTypes = null; if (baseType != null || interfaceTypes != null) { baseTypes = new List<BaseTypeSyntax>(); if (baseType != null) { baseTypes.Add(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)); } if (interfaceTypes != null) { baseTypes.AddRange(interfaceTypes.Select(i => SyntaxFactory.SimpleBaseType((TypeSyntax)i))); } if (baseTypes.Count == 0) { baseTypes = null; } } return SyntaxFactory.ClassDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ClassDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), baseTypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(baseTypes)) : null, default, this.AsClassMembers(name, members)); } private SyntaxList<MemberDeclarationSyntax> AsClassMembers(string className, IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(m => this.AsClassMember(m, className)).Where(m => m != null)) : default; } private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: node = ((ConstructorDeclarationSyntax)node).WithIdentifier(className.ToIdentifierToken()); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: node = this.AsIsolatedDeclaration(node); break; } return node as MemberDeclarationSyntax; } public override SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.StructDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.StructDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsClassMembers(name, members)); } public override SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.InterfaceDeclaration( default, AsModifierList(accessibility, DeclarationModifiers.None), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsInterfaceMembers(members)); } private SyntaxList<MemberDeclarationSyntax> AsInterfaceMembers(IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(this.AsInterfaceMember).OfType<MemberDeclarationSyntax>()) : default; } internal override SyntaxNode AsInterfaceMember(SyntaxNode m) { return this.Isolate(m, member => { Accessibility acc; DeclarationModifiers modifiers; switch (member.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member) .WithModifiers(default) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) .WithBody(null); case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)member; return property .WithModifiers(default) .WithAccessorList(WithoutBodies(property.AccessorList)); case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)member; return indexer .WithModifiers(default) .WithAccessorList(WithoutBodies(indexer.AccessorList)); // convert event into field event case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)member; return this.EventDeclaration( ev.Identifier.ValueText, ev.Type, Accessibility.NotApplicable, DeclarationModifiers.None); case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)member; return ef.WithModifiers(default); // convert field into property case SyntaxKind.FieldDeclaration: var f = (FieldDeclarationSyntax)member; SyntaxFacts.GetAccessibilityAndModifiers(f.Modifiers, out acc, out modifiers, out _); return this.AsInterfaceMember( this.PropertyDeclaration(this.GetName(f), this.ClearTrivia(this.GetType(f)), acc, modifiers, getAccessorStatements: null, setAccessorStatements: null)); default: return null; } }); } public override SyntaxNode EnumDeclaration( string name, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> members) { return EnumDeclaration(name, underlyingType: null, accessibility, modifiers, members); } internal override SyntaxNode EnumDeclaration(string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null) { return SyntaxFactory.EnumDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EnumDeclaration), name.ToIdentifierToken(), underlyingType != null ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)underlyingType))) : null, this.AsEnumMembers(members)); } public override SyntaxNode EnumMember(string name, SyntaxNode expression) { return SyntaxFactory.EnumMemberDeclaration( default, name.ToIdentifierToken(), expression != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)expression) : null); } private EnumMemberDeclarationSyntax AsEnumMember(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.IdentifierName: var id = (IdentifierNameSyntax)node; return (EnumMemberDeclarationSyntax)this.EnumMember(id.Identifier.ToString(), null); case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)node; if (fd.Declaration.Variables.Count == 1) { var vd = fd.Declaration.Variables[0]; return (EnumMemberDeclarationSyntax)this.EnumMember(vd.Identifier.ToString(), vd.Initializer?.Value); } break; } return (EnumMemberDeclarationSyntax)node; } private SeparatedSyntaxList<EnumMemberDeclarationSyntax> AsEnumMembers(IEnumerable<SyntaxNode> members) => members != null ? SyntaxFactory.SeparatedList(members.Select(this.AsEnumMember)) : default; public override SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default) { return SyntaxFactory.DelegateDeclaration( default, AsModifierList(accessibility, modifiers), returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), AsParameterList(parameters), default); } public override SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments) => AsAttributeList(SyntaxFactory.Attribute((NameSyntax)name, AsAttributeArgumentList(attributeArguments))); public override SyntaxNode AttributeArgument(string name, SyntaxNode expression) { return name != null ? SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(name.ToIdentifierName()), null, (ExpressionSyntax)expression) : SyntaxFactory.AttributeArgument((ExpressionSyntax)expression); } private static AttributeArgumentListSyntax AsAttributeArgumentList(IEnumerable<SyntaxNode> arguments) { if (arguments != null) { return SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AsAttributeArgument))); } else { return null; } } private static AttributeArgumentSyntax AsAttributeArgument(SyntaxNode node) { if (node is ExpressionSyntax expr) { return SyntaxFactory.AttributeArgument(expr); } if (node is ArgumentSyntax arg && arg.Expression != null) { return SyntaxFactory.AttributeArgument(null, arg.NameColon, arg.Expression); } return (AttributeArgumentSyntax)node; } public override TNode ClearTrivia<TNode>(TNode node) { if (node != null) { return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker); } else { return null; } } private static SyntaxList<AttributeListSyntax> AsAttributeLists(IEnumerable<SyntaxNode> attributes) { if (attributes != null) { return SyntaxFactory.List(attributes.Select(AsAttributeList)); } else { return default; } } private static AttributeListSyntax AsAttributeList(SyntaxNode node) { if (node is AttributeSyntax attr) { return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attr)); } else { return (AttributeListSyntax)node; } } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declAttributes = new(); public override IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration) { if (!s_declAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => !IsReturnAttribute(al)))); } return attrs; } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declReturnAttributes = new(); public override IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration) { if (!s_declReturnAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declReturnAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => IsReturnAttribute(al)))); } return attrs; } private static bool IsReturnAttribute(AttributeListSyntax list) => list.Target?.Identifier.IsKind(SyntaxKind.ReturnKeyword) ?? false; public override SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) => this.Isolate(declaration, d => this.InsertAttributesInternal(d, index, attributes)); private SyntaxNode InsertAttributesInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsAttributeLists(attributes); var existingAttributes = this.GetAttributes(declaration); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(declaration, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(declaration, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = declaration.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(declaration, newList); } } public override SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: return this.Isolate(declaration, d => this.InsertReturnAttributesInternal(d, index, attributes)); default: return declaration; } } private SyntaxNode InsertReturnAttributesInternal(SyntaxNode d, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsReturnAttributes(attributes); var existingAttributes = this.GetReturnAttributes(d); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(d, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(d, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = d.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(d, newList); } } private static IEnumerable<AttributeListSyntax> AsReturnAttributes(IEnumerable<SyntaxNode> attributes) { return AsAttributeLists(attributes) .Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword)))); } private static SyntaxList<AttributeListSyntax> AsAssemblyAttributes(IEnumerable<AttributeListSyntax> attributes) { return SyntaxFactory.List( attributes.Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))))); } public override IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration) { switch (attributeDeclaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)attributeDeclaration; if (list.Attributes.Count == 1) { return this.GetAttributeArguments(list.Attributes[0]); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)attributeDeclaration; if (attr.ArgumentList != null) { return attr.ArgumentList.Arguments; } break; } return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertAttributeArguments(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) => this.Isolate(declaration, d => InsertAttributeArgumentsInternal(d, index, attributeArguments)); private static SyntaxNode InsertAttributeArgumentsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) { var newArgumentList = AsAttributeArgumentList(attributeArguments); var existingArgumentList = GetAttributeArgumentList(declaration); if (existingArgumentList == null) { return WithAttributeArgumentList(declaration, newArgumentList); } else if (newArgumentList != null) { return WithAttributeArgumentList(declaration, existingArgumentList.WithArguments(existingArgumentList.Arguments.InsertRange(index, newArgumentList.Arguments))); } else { return declaration; } } private static AttributeArgumentListSyntax GetAttributeArgumentList(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return list.Attributes[0].ArgumentList; } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.ArgumentList; } return null; } private static SyntaxNode WithAttributeArgumentList(SyntaxNode declaration, AttributeArgumentListSyntax argList) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return ReplaceWithTrivia(declaration, list.Attributes[0], list.Attributes[0].WithArgumentList(argList)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.WithArgumentList(argList); } return declaration; } internal static SyntaxList<AttributeListSyntax> GetAttributeLists(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, StatementSyntax statement => statement.AttributeLists, _ => default, }; private static SyntaxNode WithAttributeLists(SyntaxNode declaration, SyntaxList<AttributeListSyntax> attributeLists) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithAttributeLists(attributeLists), AccessorDeclarationSyntax accessor => accessor.WithAttributeLists(attributeLists), ParameterSyntax parameter => parameter.WithAttributeLists(attributeLists), CompilationUnitSyntax compilationUnit => compilationUnit.WithAttributeLists(AsAssemblyAttributes(attributeLists)), StatementSyntax statement => statement.WithAttributeLists(attributeLists), _ => declaration, }; internal override ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration) => declaration is BaseTypeDeclarationSyntax baseType && baseType.BaseList != null ? ImmutableArray.Create<SyntaxNode>(baseType.BaseList) : ImmutableArray<SyntaxNode>.Empty; public override IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.Usings, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Usings, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) => PreserveTrivia(declaration, d => this.InsertNamespaceImportsInternal(d, index, imports)); private SyntaxNode InsertNamespaceImportsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) { var usingsToInsert = this.AsUsingDirectives(imports); return declaration switch { CompilationUnitSyntax cu => cu.WithUsings(cu.Usings.InsertRange(index, usingsToInsert)), BaseNamespaceDeclarationSyntax nd => nd.WithUsings(nd.Usings.InsertRange(index, usingsToInsert)), _ => declaration, }; } public override IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration) => Flatten(declaration switch { TypeDeclarationSyntax type => type.Members, EnumDeclarationSyntax @enum => @enum.Members, BaseNamespaceDeclarationSyntax @namespace => @namespace.Members, CompilationUnitSyntax compilationUnit => compilationUnit.Members, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }); private static ImmutableArray<SyntaxNode> Flatten(IEnumerable<SyntaxNode> declarations) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var declaration in declarations) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: FlattenDeclaration(builder, declaration, ((FieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.EventFieldDeclaration: FlattenDeclaration(builder, declaration, ((EventFieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.LocalDeclarationStatement: FlattenDeclaration(builder, declaration, ((LocalDeclarationStatementSyntax)declaration).Declaration); break; case SyntaxKind.VariableDeclaration: FlattenDeclaration(builder, declaration, (VariableDeclarationSyntax)declaration); break; case SyntaxKind.AttributeList: var attrList = (AttributeListSyntax)declaration; if (attrList.Attributes.Count > 1) { builder.AddRange(attrList.Attributes); } else { builder.Add(attrList); } break; default: builder.Add(declaration); break; } } return builder.ToImmutableAndFree(); static void FlattenDeclaration(ArrayBuilder<SyntaxNode> builder, SyntaxNode declaration, VariableDeclarationSyntax variableDeclaration) { if (variableDeclaration.Variables.Count > 1) { builder.AddRange(variableDeclaration.Variables); } else { builder.Add(declaration); } } } private static int GetDeclarationCount(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables.Count, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables.Count, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes.Count, _ => 1, }; private static SyntaxNode EnsureRecordDeclarationHasBody(SyntaxNode declaration) { if (declaration is RecordDeclarationSyntax recordDeclaration) { return recordDeclaration .WithSemicolonToken(default) .WithOpenBraceToken(recordDeclaration.OpenBraceToken == default ? SyntaxFactory.Token(SyntaxKind.OpenBraceToken) : recordDeclaration.OpenBraceToken) .WithCloseBraceToken(recordDeclaration.CloseBraceToken == default ? SyntaxFactory.Token(SyntaxKind.CloseBraceToken) : recordDeclaration.CloseBraceToken); } return declaration; } public override SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members) { declaration = EnsureRecordDeclarationHasBody(declaration); var newMembers = this.AsMembersOf(declaration, members); var existingMembers = this.GetMembers(declaration); if (index >= 0 && index < existingMembers.Count) { return this.InsertNodesBefore(declaration, existingMembers[index], newMembers); } else if (existingMembers.Count > 0) { return this.InsertNodesAfter(declaration, existingMembers[existingMembers.Count - 1], newMembers); } else { return declaration switch { TypeDeclarationSyntax type => type.WithMembers(type.Members.AddRange(newMembers)), EnumDeclarationSyntax @enum => @enum.WithMembers(@enum.Members.AddRange(newMembers.OfType<EnumMemberDeclarationSyntax>())), BaseNamespaceDeclarationSyntax @namespace => @namespace.WithMembers(@namespace.Members.AddRange(newMembers)), CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(compilationUnit.Members.AddRange(newMembers)), _ => declaration, }; } } private IEnumerable<MemberDeclarationSyntax> AsMembersOf(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => members?.Select(m => this.AsMemberOf(declaration, m)).OfType<MemberDeclarationSyntax>(); private SyntaxNode AsMemberOf(SyntaxNode declaration, SyntaxNode member) => declaration switch { InterfaceDeclarationSyntax => this.AsInterfaceMember(member), TypeDeclarationSyntax typeDeclaration => this.AsClassMember(member, typeDeclaration.Identifier.Text), EnumDeclarationSyntax => this.AsEnumMember(member), BaseNamespaceDeclarationSyntax => AsNamespaceMember(member), CompilationUnitSyntax => AsNamespaceMember(member), _ => null, }; public override Accessibility GetAccessibility(SyntaxNode declaration) => SyntaxFacts.GetAccessibility(declaration); public override SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility) { if (!SyntaxFacts.CanHaveAccessibility(declaration) && accessibility != Accessibility.NotApplicable) { return declaration; } return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out _, out var modifiers, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } private static readonly DeclarationModifiers s_fieldModifiers = DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.Volatile; private static readonly DeclarationModifiers s_methodModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_constructorModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_destructorModifiers = DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_propertyModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventFieldModifiers = DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_indexerModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_classModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_recordModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_structModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Ref | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_interfaceModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_accessorModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual; private static readonly DeclarationModifiers s_localFunctionModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static | DeclarationModifiers.Extern; private static readonly DeclarationModifiers s_lambdaModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static; private static DeclarationModifiers GetAllowedModifiers(SyntaxKind kind) { switch (kind) { case SyntaxKind.RecordDeclaration: return s_recordModifiers; case SyntaxKind.ClassDeclaration: return s_classModifiers; case SyntaxKind.EnumDeclaration: return DeclarationModifiers.New; case SyntaxKind.DelegateDeclaration: return DeclarationModifiers.New | DeclarationModifiers.Unsafe; case SyntaxKind.InterfaceDeclaration: return s_interfaceModifiers; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return s_structModifiers; case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return s_methodModifiers; case SyntaxKind.ConstructorDeclaration: return s_constructorModifiers; case SyntaxKind.DestructorDeclaration: return s_destructorModifiers; case SyntaxKind.FieldDeclaration: return s_fieldModifiers; case SyntaxKind.PropertyDeclaration: return s_propertyModifiers; case SyntaxKind.IndexerDeclaration: return s_indexerModifiers; case SyntaxKind.EventFieldDeclaration: return s_eventFieldModifiers; case SyntaxKind.EventDeclaration: return s_eventModifiers; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return s_accessorModifiers; case SyntaxKind.LocalFunctionStatement: return s_localFunctionModifiers; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return s_lambdaModifiers; case SyntaxKind.EnumMemberDeclaration: case SyntaxKind.Parameter: case SyntaxKind.LocalDeclarationStatement: default: return DeclarationModifiers.None; } } public override DeclarationModifiers GetModifiers(SyntaxNode declaration) { var modifierTokens = SyntaxFacts.GetModifierTokens(declaration); SyntaxFacts.GetAccessibilityAndModifiers(modifierTokens, out _, out var modifiers, out _); return modifiers; } public override SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers) => this.Isolate(declaration, d => this.WithModifiersInternal(d, modifiers)); private SyntaxNode WithModifiersInternal(SyntaxNode declaration, DeclarationModifiers modifiers) { modifiers &= GetAllowedModifiers(declaration.Kind()); var existingModifiers = this.GetModifiers(declaration); if (modifiers != existingModifiers) { return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out var accessibility, out var tmp, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } else { // no change return declaration; } } private static SyntaxNode SetModifierTokens(SyntaxNode declaration, SyntaxTokenList modifiers) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithModifiers(modifiers), ParameterSyntax parameter => parameter.WithModifiers(modifiers), LocalDeclarationStatementSyntax localDecl => localDecl.WithModifiers(modifiers), LocalFunctionStatementSyntax localFunc => localFunc.WithModifiers(modifiers), AccessorDeclarationSyntax accessor => accessor.WithModifiers(modifiers), AnonymousFunctionExpressionSyntax anonymous => anonymous.WithModifiers(modifiers), _ => declaration, }; private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers, SyntaxKind kind) => AsModifierList(accessibility, GetAllowedModifiers(kind) & modifiers); private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var list); switch (accessibility) { case Accessibility.Internal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.Public: list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Private: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.Protected: list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedOrInternal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedAndInternal: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.NotApplicable: break; } if (modifiers.IsAbstract) list.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); if (modifiers.IsNew) list.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); if (modifiers.IsSealed) list.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); if (modifiers.IsOverride) list.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); if (modifiers.IsVirtual) list.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); if (modifiers.IsStatic) list.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); if (modifiers.IsAsync) list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (modifiers.IsConst) list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); if (modifiers.IsReadOnly) list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); if (modifiers.IsUnsafe) list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); if (modifiers.IsVolatile) list.Add(SyntaxFactory.Token(SyntaxKind.VolatileKeyword)); if (modifiers.IsExtern) list.Add(SyntaxFactory.Token(SyntaxKind.ExternKeyword)); // partial and ref must be last if (modifiers.IsRef) list.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); if (modifiers.IsPartial) list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); return SyntaxFactory.TokenList(list); } private static TypeParameterListSyntax AsTypeParameterList(IEnumerable<string> typeParameterNames) { var typeParameters = typeParameterNames != null ? SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(name => SyntaxFactory.TypeParameter(name)))) : null; if (typeParameters != null && typeParameters.Parameters.Count == 0) { typeParameters = null; } return typeParameters; } public override SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNames) { var typeParameters = AsTypeParameterList(typeParameterNames); return declaration switch { MethodDeclarationSyntax method => method.WithTypeParameterList(typeParameters), TypeDeclarationSyntax type => type.WithTypeParameterList(typeParameters), DelegateDeclarationSyntax @delegate => @delegate.WithTypeParameterList(typeParameters), _ => declaration, }; } internal override SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations) => WithAccessibility(declaration switch { MethodDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), PropertyDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), EventDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), _ => declaration, }, Accessibility.NotApplicable); private static ExplicitInterfaceSpecifierSyntax CreateExplicitInterfaceSpecifier(ImmutableArray<ISymbol> explicitInterfaceImplementations) => SyntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceImplementations[0].ContainingType.GenerateNameSyntax()); public override SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) => declaration switch { MethodDeclarationSyntax method => method.WithConstraintClauses(WithTypeConstraints(method.ConstraintClauses, typeParameterName, kinds, types)), TypeDeclarationSyntax type => type.WithConstraintClauses(WithTypeConstraints(type.ConstraintClauses, typeParameterName, kinds, types)), DelegateDeclarationSyntax @delegate => @delegate.WithConstraintClauses(WithTypeConstraints(@delegate.ConstraintClauses, typeParameterName, kinds, types)), _ => declaration, }; private static SyntaxList<TypeParameterConstraintClauseSyntax> WithTypeConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> clauses, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) { var constraints = types != null ? SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(types.Select(t => SyntaxFactory.TypeConstraint((TypeSyntax)t))) : SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(); if ((kinds & SpecialTypeConstraintKind.Constructor) != 0) { constraints = constraints.Add(SyntaxFactory.ConstructorConstraint()); } var isReferenceType = (kinds & SpecialTypeConstraintKind.ReferenceType) != 0; var isValueType = (kinds & SpecialTypeConstraintKind.ValueType) != 0; if (isReferenceType || isValueType) { constraints = constraints.Insert(0, SyntaxFactory.ClassOrStructConstraint(isReferenceType ? SyntaxKind.ClassConstraint : SyntaxKind.StructConstraint)); } var clause = clauses.FirstOrDefault(c => c.Name.Identifier.ToString() == typeParameterName); if (clause == null) { if (constraints.Count > 0) { return clauses.Add(SyntaxFactory.TypeParameterConstraintClause(typeParameterName.ToIdentifierName(), constraints)); } else { return clauses; } } else if (constraints.Count == 0) { return clauses.Remove(clause); } else { return clauses.Replace(clause, clause.WithConstraints(constraints)); } } public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) => SyntaxFacts.GetDeclarationKind(declaration); public override string GetName(SyntaxNode declaration) => declaration switch { BaseTypeDeclarationSyntax baseTypeDeclaration => baseTypeDeclaration.Identifier.ValueText, DelegateDeclarationSyntax delegateDeclaration => delegateDeclaration.Identifier.ValueText, MethodDeclarationSyntax methodDeclaration => methodDeclaration.Identifier.ValueText, BaseFieldDeclarationSyntax baseFieldDeclaration => this.GetName(baseFieldDeclaration.Declaration), PropertyDeclarationSyntax propertyDeclaration => propertyDeclaration.Identifier.ValueText, EnumMemberDeclarationSyntax enumMemberDeclaration => enumMemberDeclaration.Identifier.ValueText, EventDeclarationSyntax eventDeclaration => eventDeclaration.Identifier.ValueText, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Name.ToString(), UsingDirectiveSyntax usingDirective => usingDirective.Name.ToString(), ParameterSyntax parameter => parameter.Identifier.ValueText, LocalDeclarationStatementSyntax localDeclaration => this.GetName(localDeclaration.Declaration), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => variableDeclaration.Variables[0].Identifier.ValueText, VariableDeclaratorSyntax variableDeclarator => variableDeclarator.Identifier.ValueText, TypeParameterSyntax typeParameter => typeParameter.Identifier.ValueText, AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => attributeList.Attributes[0].Name.ToString(), AttributeSyntax attribute => attribute.Name.ToString(), _ => string.Empty }; public override SyntaxNode WithName(SyntaxNode declaration, string name) => this.Isolate(declaration, d => this.WithNameInternal(d, name)); private SyntaxNode WithNameInternal(SyntaxNode declaration, string name) { var id = name.ToIdentifierToken(); return declaration switch { BaseTypeDeclarationSyntax typeDeclaration => ReplaceWithTrivia(declaration, typeDeclaration.Identifier, id), DelegateDeclarationSyntax delegateDeclaration => ReplaceWithTrivia(declaration, delegateDeclaration.Identifier, id), MethodDeclarationSyntax methodDeclaration => ReplaceWithTrivia(declaration, methodDeclaration.Identifier, id), BaseFieldDeclarationSyntax fieldDeclaration when fieldDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, fieldDeclaration.Declaration.Variables[0].Identifier, id), PropertyDeclarationSyntax propertyDeclaration => ReplaceWithTrivia(declaration, propertyDeclaration.Identifier, id), EnumMemberDeclarationSyntax enumMemberDeclaration => ReplaceWithTrivia(declaration, enumMemberDeclaration.Identifier, id), EventDeclarationSyntax eventDeclaration => ReplaceWithTrivia(declaration, eventDeclaration.Identifier, id), BaseNamespaceDeclarationSyntax namespaceDeclaration => ReplaceWithTrivia(declaration, namespaceDeclaration.Name, this.DottedName(name)), UsingDirectiveSyntax usingDeclaration => ReplaceWithTrivia(declaration, usingDeclaration.Name, this.DottedName(name)), ParameterSyntax parameter => ReplaceWithTrivia(declaration, parameter.Identifier, id), LocalDeclarationStatementSyntax localDeclaration when localDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, localDeclaration.Declaration.Variables[0].Identifier, id), TypeParameterSyntax typeParameter => ReplaceWithTrivia(declaration, typeParameter.Identifier, id), AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => ReplaceWithTrivia(declaration, attributeList.Attributes[0].Name, this.DottedName(name)), AttributeSyntax attribute => ReplaceWithTrivia(declaration, attribute.Name, this.DottedName(name)), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, variableDeclaration.Variables[0].Identifier, id), VariableDeclaratorSyntax variableDeclarator => ReplaceWithTrivia(declaration, variableDeclarator.Identifier, id), _ => declaration }; } public override SyntaxNode GetType(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return NotVoid(((DelegateDeclarationSyntax)declaration).ReturnType); case SyntaxKind.MethodDeclaration: return NotVoid(((MethodDeclarationSyntax)declaration).ReturnType); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).Type; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).Type; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).Type; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Type; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)declaration).Declaration.Type; case SyntaxKind.VariableDeclaration: return ((VariableDeclarationSyntax)declaration).Type; case SyntaxKind.VariableDeclarator: if (declaration.Parent != null) { return this.GetType(declaration.Parent); } break; } return null; } private static TypeSyntax NotVoid(TypeSyntax type) => type is PredefinedTypeSyntax pd && pd.Keyword.IsKind(SyntaxKind.VoidKeyword) ? null : type; public override SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type) => this.Isolate(declaration, d => WithTypeInternal(d, type)); private static SyntaxNode WithTypeInternal(SyntaxNode declaration, SyntaxNode type) => declaration.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(((FieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(((EventFieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.Parameter => ((ParameterSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(((LocalDeclarationStatementSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).WithType((TypeSyntax)type), _ => declaration, }; private SyntaxNode Isolate(SyntaxNode declaration, Func<SyntaxNode, SyntaxNode> editor) { var isolated = this.AsIsolatedDeclaration(declaration); return PreserveTrivia(isolated, editor); } private SyntaxNode AsIsolatedDeclaration(SyntaxNode declaration) { if (declaration != null) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Parent != null && vd.Variables.Count == 1) { return this.AsIsolatedDeclaration(vd.Parent); } break; case SyntaxKind.VariableDeclarator: var v = (VariableDeclaratorSyntax)declaration; if (v.Parent != null && v.Parent.Parent != null) { return this.ClearTrivia(WithVariable(v.Parent.Parent, v)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent != null) { var attrList = (AttributeListSyntax)attr.Parent; return attrList.WithAttributes(SyntaxFactory.SingletonSeparatedList(attr)).WithTarget(null); } break; } } return declaration; } private static SyntaxNode WithVariable(SyntaxNode declaration, VariableDeclaratorSyntax variable) { var vd = GetVariableDeclaration(declaration); if (vd != null) { return WithVariableDeclaration(declaration, vd.WithVariables(SyntaxFactory.SingletonSeparatedList(variable))); } return declaration; } private static VariableDeclarationSyntax GetVariableDeclaration(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration, _ => null, }; private static SyntaxNode WithVariableDeclaration(SyntaxNode declaration, VariableDeclarationSyntax variables) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(variables), _ => declaration, }; private static SyntaxNode GetFullDeclaration(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (CSharpSyntaxFacts.ParentIsFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsEventFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsLocalDeclarationStatement(vd)) { return vd.Parent; } else { return vd; } case SyntaxKind.VariableDeclarator: case SyntaxKind.Attribute: if (declaration.Parent != null) { return GetFullDeclaration(declaration.Parent); } break; } return declaration; } private SyntaxNode AsNodeLike(SyntaxNode existingNode, SyntaxNode newNode) { switch (this.GetDeclarationKind(existingNode)) { case DeclarationKind.Class: case DeclarationKind.Interface: case DeclarationKind.Struct: case DeclarationKind.Enum: case DeclarationKind.Namespace: case DeclarationKind.CompilationUnit: var container = this.GetDeclaration(existingNode.Parent); if (container != null) { return this.AsMemberOf(container, newNode); } break; case DeclarationKind.Attribute: return AsAttributeList(newNode); } return newNode; } public override IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration) { var list = declaration.GetParameterList(); return list != null ? list.Parameters : declaration is SimpleLambdaExpressionSyntax simpleLambda ? new[] { simpleLambda.Parameter } : SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters) { var newParameters = AsParameterList(parameters); var currentList = declaration.GetParameterList(); if (currentList == null) { currentList = declaration.IsKind(SyntaxKind.IndexerDeclaration) ? SyntaxFactory.BracketedParameterList() : (BaseParameterListSyntax)SyntaxFactory.ParameterList(); } var newList = currentList.WithParameters(currentList.Parameters.InsertRange(index, newParameters.Parameters)); return WithParameterList(declaration, newList); } public override IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement) { var statement = switchStatement as SwitchStatementSyntax; return statement?.Sections ?? SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections) { if (!(switchStatement is SwitchStatementSyntax statement)) { return switchStatement; } var newSections = statement.Sections.InsertRange(index, switchSections.Cast<SwitchSectionSyntax>()); return AddMissingTokens(statement, recurse: false).WithSections(newSections); } private static TNode AddMissingTokens<TNode>(TNode node, bool recurse) where TNode : CSharpSyntaxNode { var rewriter = new AddMissingTokensRewriter(recurse); return (TNode)rewriter.Visit(node); } private class AddMissingTokensRewriter : CSharpSyntaxRewriter { private readonly bool _recurse; private bool _firstVisit = true; public AddMissingTokensRewriter(bool recurse) => _recurse = recurse; public override SyntaxNode Visit(SyntaxNode node) { if (!_recurse && !_firstVisit) { return node; } _firstVisit = false; return base.Visit(node); } public override SyntaxToken VisitToken(SyntaxToken token) { var rewrittenToken = base.VisitToken(token); if (!rewrittenToken.IsMissing || !CSharp.SyntaxFacts.IsPunctuationOrKeyword(token.Kind())) { return rewrittenToken; } return SyntaxFactory.Token(token.Kind()).WithTriviaFrom(rewrittenToken); } } internal override SyntaxNode GetParameterListNode(SyntaxNode declaration) => declaration.GetParameterList(); private static SyntaxNode WithParameterList(SyntaxNode declaration, BaseParameterListSyntax list) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.SimpleLambdaExpression: var lambda = (SimpleLambdaExpressionSyntax)declaration; var parameters = list.Parameters; if (parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return lambda.WithParameter(parameters[0]); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), lambda.Body) .WithLeadingTrivia(lambda.GetLeadingTrivia()) .WithTrailingTrivia(lambda.GetTrailingTrivia()); } case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((RecordDeclarationSyntax)declaration).WithParameterList((ParameterListSyntax)list); default: return declaration; } } public override SyntaxNode GetExpression(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return pd.ExpressionBody.Expression; } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return id.ExpressionBody.Expression; } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return method.ExpressionBody.Expression; } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return local.ExpressionBody.Expression; } goto default; default: return GetEqualsValue(declaration)?.Value; } } public override SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression) => this.Isolate(declaration, d => WithExpressionInternal(d, expression)); private static SyntaxNode WithExpressionInternal(SyntaxNode declaration, SyntaxNode expression) { var expr = (ExpressionSyntax)expression; switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return ReplaceWithTrivia(pd, pd.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return ReplaceWithTrivia(id, id.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return ReplaceWithTrivia(method, method.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return ReplaceWithTrivia(local, local.ExpressionBody.Expression, expr); } goto default; default: var eq = GetEqualsValue(declaration); if (eq != null) { if (expression == null) { return WithEqualsValue(declaration, null); } else { // use replace so we only change the value part. return ReplaceWithTrivia(declaration, eq.Value, expr); } } else if (expression != null) { return WithEqualsValue(declaration, SyntaxFactory.EqualsValueClause(expr)); } else { return declaration; } } } private static EqualsValueClauseSyntax GetEqualsValue(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return fd.Declaration.Variables[0].Initializer; } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.Initializer; case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ld.Declaration.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return vd.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Initializer; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Default; } return null; } private static SyntaxNode WithEqualsValue(SyntaxNode declaration, EqualsValueClauseSyntax eq) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, fd.Declaration.Variables[0], fd.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.WithInitializer(eq); case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, ld.Declaration.Variables[0], ld.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return ReplaceWithTrivia(declaration, vd.Variables[0], vd.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).WithInitializer(eq); case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).WithDefault(eq); } return declaration; } private static readonly IReadOnlyList<SyntaxNode> s_EmptyList = SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); public override IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.AnonymousMethodExpression: return (((AnonymousMethodExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.ParenthesizedLambdaExpression: return (((ParenthesizedLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.SimpleLambdaExpression: return (((SimpleLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; default: return s_EmptyList; } } public override SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) { var body = CreateBlock(statements); var somebody = statements != null ? body : null; var semicolon = statements == null ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)declaration).WithBody(body); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); default: return declaration; } } public override IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration) { var list = GetAccessorList(declaration); return list?.Accessors ?? s_EmptyList; } public override SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors) { var newAccessors = AsAccessorList(accessors, declaration.Kind()); var currentList = GetAccessorList(declaration); if (currentList == null) { if (CanHaveAccessors(declaration)) { currentList = SyntaxFactory.AccessorList(); } else { return declaration; } } var newList = currentList.WithAccessors(currentList.Accessors.InsertRange(index, newAccessors.Accessors)); return WithAccessorList(declaration, newList); } internal static AccessorListSyntax GetAccessorList(SyntaxNode declaration) => (declaration as BasePropertyDeclarationSyntax)?.AccessorList; private static bool CanHaveAccessors(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.EventDeclaration => true, _ => false, }; private static SyntaxNode WithAccessorList(SyntaxNode declaration, AccessorListSyntax accessorList) => declaration switch { BasePropertyDeclarationSyntax baseProperty => baseProperty.WithAccessorList(accessorList), _ => declaration, }; private static AccessorListSyntax AsAccessorList(IEnumerable<SyntaxNode> nodes, SyntaxKind parentKind) { return SyntaxFactory.AccessorList( SyntaxFactory.List(nodes.Select(n => AsAccessor(n, parentKind)).Where(n => n != null))); } private static AccessorDeclarationSyntax AsAccessor(SyntaxNode node, SyntaxKind parentKind) { switch (parentKind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: switch (node.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; case SyntaxKind.EventDeclaration: switch (node.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; } return null; } private static AccessorDeclarationSyntax GetAccessor(SyntaxNode declaration, SyntaxKind kind) { var accessorList = GetAccessorList(declaration); return accessorList?.Accessors.FirstOrDefault(a => a.IsKind(kind)); } private SyntaxNode WithAccessor(SyntaxNode declaration, SyntaxKind kind, AccessorDeclarationSyntax accessor) => this.WithAccessor(declaration, GetAccessorList(declaration), kind, accessor); private SyntaxNode WithAccessor(SyntaxNode declaration, AccessorListSyntax accessorList, SyntaxKind kind, AccessorDeclarationSyntax accessor) { if (accessorList != null) { var acc = accessorList.Accessors.FirstOrDefault(a => a.IsKind(kind)); if (acc != null) { return this.ReplaceNode(declaration, acc, accessor); } else if (accessor != null) { return this.ReplaceNode(declaration, accessorList, accessorList.AddAccessors(accessor)); } } return declaration; } public override IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.GetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.SetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.GetAccessorDeclaration, statements); public override SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.SetAccessorDeclaration, statements); private SyntaxNode WithAccessorStatements(SyntaxNode declaration, SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var accessor = GetAccessor(declaration, kind); if (accessor == null) { accessor = AccessorDeclaration(kind, statements); return this.WithAccessor(declaration, kind, accessor); } else { return this.WithAccessor(declaration, kind, (AccessorDeclarationSyntax)this.WithStatements(accessor, statements)); } } public override IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration) { var baseList = GetBaseList(declaration); if (baseList != null) { return baseList.Types.OfType<SimpleBaseTypeSyntax>().Select(bt => bt.Type).ToReadOnlyCollection(); } else { return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } } public override SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(0, SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } } public override SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(baseList.Types.Count, SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } } private static SyntaxNode AddBaseList(SyntaxNode declaration, BaseListSyntax baseList) { var newDecl = WithBaseList(declaration, baseList); // move trivia from type identifier to after base list return ShiftTrivia(newDecl, GetBaseList(newDecl)); } private static BaseListSyntax GetBaseList(SyntaxNode declaration) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.BaseList : null; private static SyntaxNode WithBaseList(SyntaxNode declaration, BaseListSyntax baseList) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.WithBaseList(baseList) : declaration; #endregion #region Remove, Replace, Insert public override SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode declaration, SyntaxNode newDeclaration) { newDeclaration = this.AsNodeLike(declaration, newDeclaration); if (newDeclaration == null) { return this.RemoveNode(root, declaration); } if (root.Span.Contains(declaration.Span)) { var newFullDecl = this.AsIsolatedDeclaration(newDeclaration); var fullDecl = GetFullDeclaration(declaration); // special handling for replacing at location of sub-declaration if (fullDecl != declaration && fullDecl.IsKind(newFullDecl.Kind())) { // try to replace inline if possible if (GetDeclarationCount(newFullDecl) == 1) { var newSubDecl = GetSubDeclarations(newFullDecl)[0]; if (AreInlineReplaceableSubDeclarations(declaration, newSubDecl)) { return base.ReplaceNode(root, declaration, newSubDecl); } } // replace sub declaration by splitting full declaration and inserting between var index = this.IndexOf(GetSubDeclarations(fullDecl), declaration); // replace declaration with multiple declarations return ReplaceRange(root, fullDecl, this.SplitAndReplace(fullDecl, index, new[] { newDeclaration })); } // attempt normal replace return base.ReplaceNode(root, declaration, newFullDecl); } else { return base.ReplaceNode(root, declaration, newDeclaration); } } // returns true if one sub-declaration can be replaced inline with another sub-declaration private static bool AreInlineReplaceableSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.Attribute: case SyntaxKind.VariableDeclarator: return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent); } } return false; } private static bool AreSimilarExceptForSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { if (decl1 == decl2) { return true; } if (decl1 == null || decl2 == null) { return false; } var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.FieldDeclaration: var fd1 = (FieldDeclarationSyntax)decl1; var fd2 = (FieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) && SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists); case SyntaxKind.EventFieldDeclaration: var efd1 = (EventFieldDeclarationSyntax)decl1; var efd2 = (EventFieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(efd1.Modifiers, efd2.Modifiers) && SyntaxFactory.AreEquivalent(efd1.AttributeLists, efd2.AttributeLists); case SyntaxKind.LocalDeclarationStatement: var ld1 = (LocalDeclarationStatementSyntax)decl1; var ld2 = (LocalDeclarationStatementSyntax)decl2; return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers); case SyntaxKind.AttributeList: // don't compare targets, since aren't part of the abstraction return true; case SyntaxKind.VariableDeclaration: var vd1 = (VariableDeclarationSyntax)decl1; var vd2 = (VariableDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(vd1.Type, vd2.Type) && AreSimilarExceptForSubDeclarations(vd1.Parent, vd2.Parent); } } return false; } // replaces sub-declaration by splitting multi-part declaration first private IEnumerable<SyntaxNode> SplitAndReplace(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); if (index >= 0 && index < count) { var newNodes = new List<SyntaxNode>(); if (index > 0) { // make a single declaration with only sub-declarations before the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } newNodes.AddRange(newDeclarations); if (index < count - 1) { // make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); } return newNodes; } else { return newDeclarations; } } public override SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesBefore(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesBeforeInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesBefore(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index > 0) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index, newDeclarations)); } return base.InsertNodesBefore(root, fullDecl, newDeclarations); } public override SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesAfter(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesAfterInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesAfter(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var count = subDecls.Count; var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index >= 0 && index < count - 1) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index + 1, newDeclarations)); } return base.InsertNodesAfter(root, fullDecl, newDeclarations); } private IEnumerable<SyntaxNode> SplitAndInsert(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); var newNodes = new List<SyntaxNode>(); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); newNodes.AddRange(newDeclarations); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); return newNodes; } private SyntaxNode WithSubDeclarationsRemoved(SyntaxNode declaration, int index, int count) => this.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)); private static IReadOnlyList<SyntaxNode> GetSubDeclarations(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => this.RemoveNode(root, node, DefaultRemoveOptions); public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) { if (node.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Remove the entire global statement as part of the edit node = node.Parent; } if (root.Span.Contains(node.Span)) { // node exists within normal span of the root (not in trivia) return this.Isolate(root.TrackNodes(node), r => this.RemoveNodeInternal(r, r.GetCurrentNode(node), options)); } else { return this.RemoveNodeInternal(root, node, options); } } private SyntaxNode RemoveNodeInternal(SyntaxNode root, SyntaxNode declaration, SyntaxRemoveOptions options) { switch (declaration.Kind()) { case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent is AttributeListSyntax attrList && attrList.Attributes.Count == 1) { // remove entire list if only one attribute return this.RemoveNodeInternal(root, attrList, options); } break; case SyntaxKind.AttributeArgument: if (declaration.Parent != null && ((AttributeArgumentListSyntax)declaration.Parent).Arguments.Count == 1) { // remove entire argument list if only one argument return this.RemoveNodeInternal(root, declaration.Parent, options); } break; case SyntaxKind.VariableDeclarator: var full = GetFullDeclaration(declaration); if (full != declaration && GetDeclarationCount(full) == 1) { // remove full declaration if only one declarator return this.RemoveNodeInternal(root, full, options); } break; case SyntaxKind.SimpleBaseType: if (declaration.Parent is BaseListSyntax baseList && baseList.Types.Count == 1) { // remove entire base list if this is the only base type. return this.RemoveNodeInternal(root, baseList, options); } break; default: var parent = declaration.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.SimpleBaseType: return this.RemoveNodeInternal(root, parent, options); } } break; } return base.RemoveNode(root, declaration, options); } /// <summary> /// Moves the trailing trivia from the node's previous token to the end of the node /// </summary> private static SyntaxNode ShiftTrivia(SyntaxNode root, SyntaxNode node) { var firstToken = node.GetFirstToken(); var previousToken = firstToken.GetPreviousToken(); if (previousToken != default && root.Contains(previousToken.Parent)) { var newNode = node.WithTrailingTrivia(node.GetTrailingTrivia().AddRange(previousToken.TrailingTrivia)); var newPreviousToken = previousToken.WithTrailingTrivia(default(SyntaxTriviaList)); return root.ReplaceSyntax( nodes: new[] { node }, computeReplacementNode: (o, r) => newNode, tokens: new[] { previousToken }, computeReplacementToken: (o, r) => newPreviousToken, trivia: null, computeReplacementTrivia: null); } return root; } internal override bool IsRegularOrDocComment(SyntaxTrivia trivia) => trivia.IsRegularOrDocComment(); #endregion #region Statements and Expressions public override SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode AwaitExpression(SyntaxNode expression) => SyntaxFactory.AwaitExpression((ExpressionSyntax)expression); public override SyntaxNode NameOfExpression(SyntaxNode expression) => this.InvocationExpression(s_nameOfIdentifier, expression); public override SyntaxNode ReturnStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ReturnStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ThrowStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowExpression(SyntaxNode expression) => SyntaxFactory.ThrowExpression((ExpressionSyntax)expression); internal override bool SupportsThrowExpression() => true; public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null) { if (falseStatements == null) { return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements)); } else { var falseArray = falseStatements.ToList(); // make else-if chain if false-statements contain only an if-statement return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements), SyntaxFactory.ElseClause( falseArray.Count == 1 && falseArray[0] is IfStatementSyntax ? (StatementSyntax)falseArray[0] : CreateBlock(falseArray))); } } private static BlockSyntax CreateBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(AsStatementList(statements)).WithAdditionalAnnotations(Simplifier.Annotation); private static SyntaxList<StatementSyntax> AsStatementList(IEnumerable<SyntaxNode> nodes) => nodes == null ? default : SyntaxFactory.List(nodes.Select(AsStatement)); private static StatementSyntax AsStatement(SyntaxNode node) { if (node is ExpressionSyntax expression) { return SyntaxFactory.ExpressionStatement(expression); } return (StatementSyntax)node; } public override SyntaxNode ExpressionStatement(SyntaxNode expression) => SyntaxFactory.ExpressionStatement((ExpressionSyntax)expression); internal override SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode simpleName) { return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParenthesizeLeft((ExpressionSyntax)expression), (SimpleNameSyntax)simpleName); } public override SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull) => SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull); public override SyntaxNode MemberBindingExpression(SyntaxNode name) => SyntaxGeneratorInternal.MemberBindingExpression(name); public override SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementBindingExpression( SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments))); /// <summary> /// Parenthesize the left hand size of a member access, invocation or element access expression /// </summary> private static ExpressionSyntax ParenthesizeLeft(ExpressionSyntax expression) { if (expression is TypeSyntax || expression.IsKind(SyntaxKind.ThisExpression) || expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.ParenthesizedExpression) || expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || expression.IsKind(SyntaxKind.InvocationExpression) || expression.IsKind(SyntaxKind.ElementAccessExpression) || expression.IsKind(SyntaxKind.MemberBindingExpression)) { return expression; } return (ExpressionSyntax)Parenthesize(expression); } private static SeparatedSyntaxList<ExpressionSyntax> AsExpressionList(IEnumerable<SyntaxNode> expressions) => SyntaxFactory.SeparatedList(expressions.OfType<ExpressionSyntax>()); public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)size)))); return SyntaxFactory.ArrayCreationExpression(arrayType); } public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression())))); var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, AsExpressionList(elements)); return SyntaxFactory.ArrayCreationExpression(arrayType, initializer); } public override SyntaxNode ObjectCreationExpression(SyntaxNode type, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ObjectCreationExpression((TypeSyntax)type, CreateArgumentList(arguments), null); internal override SyntaxNode ObjectCreationExpression(SyntaxNode type, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen) => SyntaxFactory.ObjectCreationExpression( (TypeSyntax)type, SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer: null); private static ArgumentListSyntax CreateArgumentList(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(CreateArguments(arguments)); private static SeparatedSyntaxList<ArgumentSyntax> CreateArguments(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.SeparatedList(arguments.Select(AsArgument)); private static ArgumentSyntax AsArgument(SyntaxNode argOrExpression) => argOrExpression as ArgumentSyntax ?? SyntaxFactory.Argument((ExpressionSyntax)argOrExpression); public override SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.InvocationExpression(ParenthesizeLeft((ExpressionSyntax)expression), CreateArgumentList(arguments)); public override SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementAccessExpression(ParenthesizeLeft((ExpressionSyntax)expression), SyntaxFactory.BracketedArgumentList(CreateArguments(arguments))); internal override SyntaxToken NumericLiteralToken(string text, ulong value) => SyntaxFactory.Literal(text, value); public override SyntaxNode DefaultExpression(SyntaxNode type) => SyntaxFactory.DefaultExpression((TypeSyntax)type).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode DefaultExpression(ITypeSymbol type) { // If it's just a reference type, then "null" is the default expression for it. Note: // this counts for actual reference type, or a type parameter with a 'class' constraint. // Also, if it's a nullable type, then we can use "null". if (type.IsReferenceType || type.IsPointerType() || type.IsNullable()) { return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); } switch (type.SpecialType) { case SpecialType.System_Boolean: return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0)); } // Default to a "default(<typename>)" expression. return DefaultExpression(type.GenerateTypeSyntax()); } private static SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => CSharpSyntaxGeneratorInternal.Parenthesize(expression, includeElasticTrivia, addSimplifierAnnotation); public override SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.IsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode TypeOfExpression(SyntaxNode type) => SyntaxFactory.TypeOfExpression((TypeSyntax)type); public override SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)left, (ExpressionSyntax)Parenthesize(right)); private static SyntaxNode CreateBinaryExpression(SyntaxKind syntaxKind, SyntaxNode left, SyntaxNode right) => SyntaxFactory.BinaryExpression(syntaxKind, (ExpressionSyntax)Parenthesize(left), (ExpressionSyntax)Parenthesize(right)); public override SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanExpression, left, right); public override SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); public override SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanExpression, left, right); public override SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); public override SyntaxNode NegateExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.AddExpression, left, right); public override SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.SubtractExpression, left, right); public override SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.MultiplyExpression, left, right); public override SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.DivideExpression, left, right); public override SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.ModuloExpression, left, right); public override SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); public override SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); public override SyntaxNode BitwiseNotExpression(SyntaxNode operand) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, (ExpressionSyntax)Parenthesize(operand)); public override SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalAndExpression, left, right); public override SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalOrExpression, left, right); public override SyntaxNode LogicalNotExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse) => SyntaxFactory.ConditionalExpression((ExpressionSyntax)Parenthesize(condition), (ExpressionSyntax)Parenthesize(whenTrue), (ExpressionSyntax)Parenthesize(whenFalse)); public override SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.CoalesceExpression, left, right); public override SyntaxNode ThisExpression() => SyntaxFactory.ThisExpression(); public override SyntaxNode BaseExpression() => SyntaxFactory.BaseExpression(); public override SyntaxNode LiteralExpression(object value) => ExpressionGenerator.GenerateNonEnumValueExpression(null, value, canUseFieldReference: true); public override SyntaxNode TypedConstantExpression(TypedConstant value) => ExpressionGenerator.GenerateExpression(value); public override SyntaxNode IdentifierName(string identifier) => identifier.ToIdentifierName(); public override SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments) => GenericName(identifier.ToIdentifierToken(), typeArguments); internal override SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments) => SyntaxFactory.GenericName(identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); public override SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments) { switch (expression.Kind()) { case SyntaxKind.IdentifierName: var sname = (SimpleNameSyntax)expression; return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.GenericName: var gname = (GenericNameSyntax)expression; return gname.WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.QualifiedName: var qname = (QualifiedNameSyntax)expression; return qname.WithRight((SimpleNameSyntax)this.WithTypeArguments(qname.Right, typeArguments)); case SyntaxKind.AliasQualifiedName: var aname = (AliasQualifiedNameSyntax)expression; return aname.WithName((SimpleNameSyntax)this.WithTypeArguments(aname.Name, typeArguments)); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var sma = (MemberAccessExpressionSyntax)expression; return sma.WithName((SimpleNameSyntax)this.WithTypeArguments(sma.Name, typeArguments)); default: return expression; } } public override SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right) => SyntaxFactory.QualifiedName((NameSyntax)left, (SimpleNameSyntax)right).WithAdditionalAnnotations(Simplifier.Annotation); internal override SyntaxNode GlobalAliasedName(SyntaxNode name) => SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)name); public override SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol) => namespaceOrTypeSymbol.GenerateNameSyntax(); public override SyntaxNode TypeExpression(ITypeSymbol typeSymbol) => typeSymbol.GenerateTypeSyntax(); public override SyntaxNode TypeExpression(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)), SpecialType.System_Byte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)), SpecialType.System_Char => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)), SpecialType.System_Decimal => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)), SpecialType.System_Double => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)), SpecialType.System_Int16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)), SpecialType.System_Int32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)), SpecialType.System_Int64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)), SpecialType.System_Object => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), SpecialType.System_SByte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)), SpecialType.System_Single => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.FloatKeyword)), SpecialType.System_String => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SpecialType.System_UInt16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)), SpecialType.System_UInt32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntKeyword)), SpecialType.System_UInt64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)), _ => throw new NotSupportedException("Unsupported SpecialType"), }; public override SyntaxNode ArrayTypeExpression(SyntaxNode type) => SyntaxFactory.ArrayType((TypeSyntax)type, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())); public override SyntaxNode NullableTypeExpression(SyntaxNode type) { if (type is NullableTypeSyntax) { return type; } else { return SyntaxFactory.NullableType((TypeSyntax)type); } } internal override SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements) => SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast<TupleElementSyntax>())); public override SyntaxNode TupleElementExpression(SyntaxNode type, string name = null) => SyntaxFactory.TupleElement((TypeSyntax)type, name?.ToIdentifierToken() ?? default); public override SyntaxNode Argument(string nameOpt, RefKind refKind, SyntaxNode expression) { return SyntaxFactory.Argument( nameOpt == null ? null : SyntaxFactory.NameColon(nameOpt), GetArgumentModifiers(refKind), (ExpressionSyntax)expression); } public override SyntaxNode LocalDeclarationStatement(SyntaxNode type, string name, SyntaxNode initializer, bool isConst) => CSharpSyntaxGeneratorInternal.Instance.LocalDeclarationStatement(type, name.ToIdentifierToken(), initializer, isConst); public override SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( CSharpSyntaxGeneratorInternal.VariableDeclaration(type, name.ToIdentifierToken(), expression), expression: null, statement: CreateBlock(statements)); } public override SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( declaration: null, expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.LockStatement( expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null) { return SyntaxFactory.TryStatement( CreateBlock(tryStatements), catchClauses != null ? SyntaxFactory.List(catchClauses.Cast<CatchClauseSyntax>()) : default, finallyStatements != null ? SyntaxFactory.FinallyClause(CreateBlock(finallyStatements)) : null); } public override SyntaxNode CatchClause(SyntaxNode type, string name, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.CatchClause( SyntaxFactory.CatchDeclaration((TypeSyntax)type, name.ToIdentifierToken()), filter: null, block: CreateBlock(statements)); } public override SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements) => SyntaxFactory.WhileStatement((ExpressionSyntax)condition, CreateBlock(statements)); public override SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> caseClauses) { if (expression is TupleExpressionSyntax) { return SyntaxFactory.SwitchStatement( (ExpressionSyntax)expression, caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList()); } else { return SyntaxFactory.SwitchStatement( SyntaxFactory.Token(SyntaxKind.SwitchKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), (ExpressionSyntax)expression, SyntaxFactory.Token(SyntaxKind.CloseParenToken), SyntaxFactory.Token(SyntaxKind.OpenBraceToken), caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList(), SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } } public override SyntaxNode SwitchSection(IEnumerable<SyntaxNode> expressions, IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(AsSwitchLabels(expressions), AsStatementList(statements)); internal override SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.SwitchSection( labels.Cast<SwitchLabelSyntax>().ToSyntaxList(), AsStatementList(statements)); } public override SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(SyntaxFactory.SingletonList(SyntaxFactory.DefaultSwitchLabel() as SwitchLabelSyntax), AsStatementList(statements)); private static SyntaxList<SwitchLabelSyntax> AsSwitchLabels(IEnumerable<SyntaxNode> expressions) { var labels = default(SyntaxList<SwitchLabelSyntax>); if (expressions != null) { labels = labels.AddRange(expressions.Select(e => SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)e))); } return labels; } public override SyntaxNode ExitSwitchStatement() => SyntaxFactory.BreakStatement(); internal override SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(statements.Cast<StatementSyntax>()); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, SyntaxNode expression) { var parameters = parameterDeclarations?.Cast<ParameterSyntax>().ToList(); if (parameters != null && parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return SyntaxFactory.SimpleLambdaExpression(parameters[0], (CSharpSyntaxNode)expression); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), (CSharpSyntaxNode)expression); } } private static bool IsSimpleLambdaParameter(SyntaxNode node) => node is ParameterSyntax p && p.Type == null && p.Default == null && p.Modifiers.Count == 0; public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression) => this.ValueReturningLambdaExpression(lambdaParameters, expression); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(parameterDeclarations, CreateBlock(statements)); public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(lambdaParameters, statements); public override SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null) => this.ParameterDeclaration(identifier, type, null, RefKind.None); internal override SyntaxNode IdentifierName(SyntaxToken identifier) => SyntaxFactory.IdentifierName(identifier); internal override SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression) { return SyntaxFactory.AnonymousObjectMemberDeclarator( SyntaxFactory.NameEquals((IdentifierNameSyntax)identifier), (ExpressionSyntax)expression); } public override SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AsArgument))); internal override SyntaxNode RemoveAllComments(SyntaxNode node) { var modifiedNode = RemoveLeadingAndTrailingComments(node); if (modifiedNode is TypeDeclarationSyntax declarationSyntax) { return declarationSyntax.WithOpenBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.OpenBraceToken)) .WithCloseBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.CloseBraceToken)); } return modifiedNode; } internal override SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList) { static IEnumerable<IEnumerable<SyntaxTrivia>> splitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } var syntaxWithoutComments = splitIntoLines(syntaxTriviaList) .Where(trivia => !trivia.Any(t => t.IsRegularOrDocComment())) .SelectMany(t => t); return new SyntaxTriviaList(syntaxWithoutComments); } internal override SyntaxNode ParseExpression(string stringToParse) => SyntaxFactory.ParseExpression(stringToParse); #endregion } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/NamespaceGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (!(declaration is NamespaceDeclarationSyntax)) { throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); } var members = Insert(destination.Members, (NamespaceDeclarationSyntax)declaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.CompilationUnit => ((CompilationUnitSyntax)declaration).WithMembers(default), SyntaxKind.NamespaceDeclaration => ((NamespaceDeclarationSyntax)declaration).WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default), BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports { internal partial class CSharpOrganizeImportsService { private class Rewriter : CSharpSyntaxRewriter { private readonly bool _placeSystemNamespaceFirst; private readonly bool _separateGroups; public readonly IList<TextChange> TextChanges = new List<TextChange>(); public Rewriter(bool placeSystemNamespaceFirst, bool separateGroups) { _placeSystemNamespaceFirst = placeSystemNamespaceFirst; _separateGroups = separateGroups; } public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { node = (CompilationUnitSyntax)base.VisitCompilationUnit(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) { node = (NamespaceDeclarationSyntax)base.VisitNamespaceDeclaration(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { if (list.Count > 0) { this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList))); } } private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { return string.Join(string.Empty, organizedList.Select(t => t.ToFullString())); } private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode { return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports { internal partial class CSharpOrganizeImportsService { private class Rewriter : CSharpSyntaxRewriter { private readonly bool _placeSystemNamespaceFirst; private readonly bool _separateGroups; public readonly IList<TextChange> TextChanges = new List<TextChange>(); public Rewriter(bool placeSystemNamespaceFirst, bool separateGroups) { _placeSystemNamespaceFirst = placeSystemNamespaceFirst; _separateGroups = separateGroups; } public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!; UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node)); public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node)); private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node) { Contract.ThrowIfNull(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { if (list.Count > 0) this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList))); } private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode => string.Join(string.Empty, organizedList.Select(t => t.ToFullString())); private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode => TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End); } } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1;|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1;|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetSyntaxRootAsync(); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task FileScopedNamespace() { var initial = @"using B; using A; namespace N; using D; using C; "; var final = @"using A; using B; namespace N; using C; using D; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } } }
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/AbstractSyntaxFormattingService.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class AbstractSyntaxFormattingService : ISyntaxFormattingService { private static readonly Func<TextSpan, bool> s_notEmpty = s => !s.IsEmpty; private static readonly Func<TextSpan, int> s_spanLength = s => s.Length; protected AbstractSyntaxFormattingService() { } public abstract IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules(); protected abstract IFormattingResult CreateAggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans = null); protected abstract AbstractFormattingResult Format(SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, SyntaxToken token1, SyntaxToken token2, CancellationToken cancellationToken); public IFormattingResult Format(SyntaxNode node, IEnumerable<TextSpan> spans, bool shouldUseFormattingSpanCollapse, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, CancellationToken cancellationToken) { CheckArguments(node, spans, options, rules); // quick exit check var spansToFormat = new NormalizedTextSpanCollection(spans.Where(s_notEmpty)); if (spansToFormat.Count == 0) { return CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList<AbstractFormattingResult>()); } // check what kind of formatting strategy to use if (AllowDisjointSpanMerging(spansToFormat, shouldUseFormattingSpanCollapse)) { return FormatMergedSpan(node, options, rules, spansToFormat, cancellationToken); } return FormatIndividually(node, options, rules, spansToFormat, cancellationToken); } private IFormattingResult FormatMergedSpan( SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, IList<TextSpan> spansToFormat, CancellationToken cancellationToken) { var spanToFormat = TextSpan.FromBounds(spansToFormat[0].Start, spansToFormat[spansToFormat.Count - 1].End); var pair = node.ConvertToTokenPair(spanToFormat); if (node.IsInvalidTokenRange(pair.Item1, pair.Item2)) { return CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList<AbstractFormattingResult>()); } // more expensive case var result = Format(node, options, rules, pair.Item1, pair.Item2, cancellationToken); return CreateAggregatedFormattingResult(node, new List<AbstractFormattingResult>(1) { result }, SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), spanToFormat)); } private IFormattingResult FormatIndividually( SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, IList<TextSpan> spansToFormat, CancellationToken cancellationToken) { List<AbstractFormattingResult>? results = null; foreach (var pair in node.ConvertToTokenPairs(spansToFormat)) { if (node.IsInvalidTokenRange(pair.Item1, pair.Item2)) { continue; } results ??= new List<AbstractFormattingResult>(); results.Add(Format(node, options, rules, pair.Item1, pair.Item2, cancellationToken)); } // quick simple case check if (results == null) { return CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList<AbstractFormattingResult>()); } if (results.Count == 1) { return results[0]; } // more expensive case return CreateAggregatedFormattingResult(node, results); } private static bool AllowDisjointSpanMerging(IList<TextSpan> list, bool shouldUseFormattingSpanCollapse) { // If the user is specific about the formatting specific spans then honor users settings if (!shouldUseFormattingSpanCollapse) { return false; } // most common case. it is either just formatting a whole file, a selection or some generate XXX refactoring. if (list.Count <= 3) { // don't collapse formatting spans return false; } // too many formatting spans, just collapse them and format at once if (list.Count > 30) { // figuring out base indentation at random place in a file takes about 2ms. // doing 30 times will make it cost about 60ms. that is about same cost, for the same file, engine will // take to create full formatting context. basically after that, creating full context is cheaper than // doing bottom up base indentation calculation for each span. return true; } // check how much area we are formatting var formattingSpan = TextSpan.FromBounds(list[0].Start, list[list.Count - 1].End); var actualFormattingSize = list.Sum(s_spanLength); // we are formatting more than half of the collapsed span. return (formattingSpan.Length / Math.Max(actualFormattingSize, 1)) < 2; } private static void CheckArguments(SyntaxNode node, IEnumerable<TextSpan> spans, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (spans == null) { throw new ArgumentNullException(nameof(spans)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (rules == null) { throw new ArgumentNullException(nameof(rules)); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class AbstractSyntaxFormattingService : ISyntaxFormattingService { private static readonly Func<TextSpan, bool> s_notEmpty = s => !s.IsEmpty; private static readonly Func<TextSpan, int> s_spanLength = s => s.Length; protected AbstractSyntaxFormattingService() { } public abstract IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules(); protected abstract IFormattingResult CreateAggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans = null); protected abstract AbstractFormattingResult Format(SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, SyntaxToken token1, SyntaxToken token2, CancellationToken cancellationToken); public IFormattingResult Format(SyntaxNode node, IEnumerable<TextSpan> spans, bool shouldUseFormattingSpanCollapse, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, CancellationToken cancellationToken) { CheckArguments(node, spans, options, rules); // quick exit check var spansToFormat = new NormalizedTextSpanCollection(spans.Where(s_notEmpty)); if (spansToFormat.Count == 0) { return CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList<AbstractFormattingResult>()); } // check what kind of formatting strategy to use if (AllowDisjointSpanMerging(spansToFormat, shouldUseFormattingSpanCollapse)) { return FormatMergedSpan(node, options, rules, spansToFormat, cancellationToken); } return FormatIndividually(node, options, rules, spansToFormat, cancellationToken); } private IFormattingResult FormatMergedSpan( SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, IList<TextSpan> spansToFormat, CancellationToken cancellationToken) { var spanToFormat = TextSpan.FromBounds(spansToFormat[0].Start, spansToFormat[spansToFormat.Count - 1].End); var pair = node.ConvertToTokenPair(spanToFormat); if (node.IsInvalidTokenRange(pair.Item1, pair.Item2)) { return CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList<AbstractFormattingResult>()); } // more expensive case var result = Format(node, options, rules, pair.Item1, pair.Item2, cancellationToken); return CreateAggregatedFormattingResult(node, new List<AbstractFormattingResult>(1) { result }, SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), spanToFormat)); } private IFormattingResult FormatIndividually( SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, IList<TextSpan> spansToFormat, CancellationToken cancellationToken) { List<AbstractFormattingResult>? results = null; foreach (var pair in node.ConvertToTokenPairs(spansToFormat)) { if (node.IsInvalidTokenRange(pair.Item1, pair.Item2)) { continue; } results ??= new List<AbstractFormattingResult>(); results.Add(Format(node, options, rules, pair.Item1, pair.Item2, cancellationToken)); } // quick simple case check if (results == null) { return CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList<AbstractFormattingResult>()); } if (results.Count == 1) { return results[0]; } // more expensive case return CreateAggregatedFormattingResult(node, results); } private static bool AllowDisjointSpanMerging(IList<TextSpan> list, bool shouldUseFormattingSpanCollapse) { // If the user is specific about the formatting specific spans then honor users settings if (!shouldUseFormattingSpanCollapse) { return false; } // most common case. it is either just formatting a whole file, a selection or some generate XXX refactoring. if (list.Count <= 3) { // don't collapse formatting spans return false; } // too many formatting spans, just collapse them and format at once if (list.Count > 30) { // figuring out base indentation at random place in a file takes about 2ms. // doing 30 times will make it cost about 60ms. that is about same cost, for the same file, engine will // take to create full formatting context. basically after that, creating full context is cheaper than // doing bottom up base indentation calculation for each span. return true; } // check how much area we are formatting var formattingSpan = TextSpan.FromBounds(list[0].Start, list[list.Count - 1].End); var actualFormattingSize = list.Sum(s_spanLength); // we are formatting more than half of the collapsed span. return (formattingSpan.Length / Math.Max(actualFormattingSize, 1)) < 2; } private static void CheckArguments(SyntaxNode node, IEnumerable<TextSpan> spans, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (spans == null) { throw new ArgumentNullException(nameof(spans)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (rules == null) { throw new ArgumentNullException(nameof(rules)); } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Storage/SQLite/Interop/SafeSqliteBlobHandle.cs
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.Shared.Extensions; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.Interop { internal sealed class SafeSqliteBlobHandle : SafeHandle { private readonly sqlite3_blob? _wrapper; private readonly SafeHandleLease _lease; private readonly SafeHandleLease _sqliteLease; public SafeSqliteBlobHandle(SafeSqliteHandle sqliteHandle, sqlite3_blob? wrapper) : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true) { _wrapper = wrapper; if (wrapper is not null) { _lease = wrapper.Lease(); SetHandle(wrapper.DangerousGetHandle()); } else { _lease = default; SetHandle(IntPtr.Zero); } _sqliteLease = sqliteHandle.Lease(); } public override bool IsInvalid => handle == IntPtr.Zero; public sqlite3_blob DangerousGetWrapper() => _wrapper!; protected override bool ReleaseHandle() { try { using var _ = _wrapper; _lease.Dispose(); SetHandle(IntPtr.Zero); return true; } finally { _sqliteLease.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.Shared.Extensions; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.Interop { internal sealed class SafeSqliteBlobHandle : SafeHandle { private readonly sqlite3_blob? _wrapper; private readonly SafeHandleLease _lease; private readonly SafeHandleLease _sqliteLease; public SafeSqliteBlobHandle(SafeSqliteHandle sqliteHandle, sqlite3_blob? wrapper) : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true) { _wrapper = wrapper; if (wrapper is not null) { _lease = wrapper.Lease(); SetHandle(wrapper.DangerousGetHandle()); } else { _lease = default; SetHandle(IntPtr.Zero); } _sqliteLease = sqliteHandle.Lease(); } public override bool IsInvalid => handle == IntPtr.Zero; public sqlite3_blob DangerousGetWrapper() => _wrapper!; protected override bool ReleaseHandle() { try { using var _ = _wrapper; _lease.Dispose(); SetHandle(IntPtr.Zero); return true; } finally { _sqliteLease.Dispose(); } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/ValueTracking/ValueTrackingTreeRootViewModel.cs
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class ValueTrackingTreeRootViewModel : TreeViewItemBase { } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class ValueTrackingTreeRootViewModel : TreeViewItemBase { } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefOutTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenRefOutTests : CSharpTestBase { [Fact] public void TestOutParamSignature() { var source = @" class C { void M(out int x) { x = 0; } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M([out] System.Int32& x) cil managed") }); } [Fact] public void TestRefParamSignature() { var source = @" class C { void M(ref int x) { } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M(System.Int32& x) cil managed") }); } [Fact] public void TestOneReferenceMultipleParameters() { var source = @" class C { static void Main() { int z = 0; Test(ref z, out z); System.Console.WriteLine(z); } static void Test(ref int x, out int y) { x = 1; y = 2; } }"; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void TestReferenceParameterOrder() { var source = @" public class Test { static int[] array = new int[1]; public static void Main(string[] args) { // Named parameters are in reversed order // Arguments have side effects // Arguments refer to the same array element Goo(y: out GetArray(""A"")[GetIndex(""B"")], x: ref GetArray(""C"")[GetIndex(""D"")]); System.Console.WriteLine(array[0]); } static void Goo(ref int x, out int y) { x = 1; y = 2; } static int GetIndex(string msg) { System.Console.WriteLine(""Index {0}"", msg); return 0; } static int[] GetArray(string msg) { System.Console.WriteLine(""Array {0}"", msg); return array; } }"; CompileAndVerify(source, expectedOutput: @" Array A Index B Array C Index D 2"); } [Fact] public void TestPassMutableStructByReference() { var source = @" class C { static void Main() { MutableStruct s1 = new MutableStruct(); s1.Dump(); ByRef(ref s1, 2); s1.Dump(); System.Console.WriteLine(); MutableStruct s2 = new MutableStruct(); s2.Dump(); ByVal(s2, 2); s2.Dump(); } static void ByRef(ref MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByRef(ref s, depth - 1); s.Dump(); } } static void ByVal(MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByVal(s, depth - 1); s.Dump(); } } } struct MutableStruct { private bool flagged; public void Flag() { this.flagged = true; } public void Dump() { System.Console.WriteLine(flagged ? ""Flagged"" : ""Unflagged""); } }"; CompileAndVerify(source, expectedOutput: @" Unflagged Unflagged Unflagged Flagged Flagged Flagged Unflagged Unflagged Unflagged Unflagged Unflagged Unflagged"); } [Fact] public void TestPassFieldByReference() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestRef(ref c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestRef(ref c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestRef(ref C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestRef(ref C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestRef(ref int x) { x++; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [Fact] public void TestSetFieldViaOutParameter() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestOut(out c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestOut(out c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestOut(out C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestOut(out C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestOut(out int x) { x = 1; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [WorkItem(543521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543521")] [Fact()] public void TestConstructorWithOutParameter() { CompileAndVerify(@" class Class1 { Class1(out bool outParam) { outParam = true; } static void Main() { var b = false; var c1 = new Class1(out b); } }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void RefExtensionMethods_OutParam() { var code = @" using System; public class C { public static void Main() { var inst = new S1(); int orig; var result = inst.Mutate(out orig); System.Console.Write(orig); System.Console.Write(inst.x); } } public static class S1_Ex { public static bool Mutate(ref this S1 instance, out int orig) { orig = instance.x; instance.x = 42; return true; } } public struct S1 { public int x; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "042"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 2 .locals init (S1 V_0, //inst int V_1) //orig IL_0000: ldloca.s V_0 IL_0002: initobj ""S1"" IL_0008: ldloca.s V_0 IL_000a: ldloca.s V_1 IL_000c: call ""bool S1_Ex.Mutate(ref S1, out int)"" IL_0011: pop IL_0012: ldloc.1 IL_0013: call ""void System.Console.Write(int)"" IL_0018: ldloc.0 IL_0019: ldfld ""int S1.x"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptional() { var code = @" using System; public class C { public static C cc => new C(); readonly int x; readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var c = C.cc.Test(1, this, out x, out y); } public C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = 2; return arg2; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 34 (0x22) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: call ""C C.cc.get"" IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldarg.0 IL_0012: ldarga.s V_1 IL_0014: ldarg.0 IL_0015: ldflda ""int C.y"" IL_001a: ldnull IL_001b: callvirt ""C C.Test(object, C, out int, out int, object)"" IL_0020: pop IL_0021: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptionalNested() { var code = @" using System; public class C { public static C cc => new C(); readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var captured = 2; C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = captured++; return arg2; } var c = Test(1, this, out x, out y); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 39 (0x27) .maxstack 6 .locals init (C.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldloca.s V_0 IL_0008: ldc.i4.2 IL_0009: stfld ""int C.<>c__DisplayClass5_0.captured"" IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldarg.0 IL_0015: ldarga.s V_1 IL_0017: ldarg.0 IL_0018: ldflda ""int C.y"" IL_001d: ldnull IL_001e: ldloca.s V_0 IL_0020: call ""C C.<.ctor>g__Test|5_0(object, C, out int, out int, object, ref C.<>c__DisplayClass5_0)"" IL_0025: pop IL_0026: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using 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.CodeGen { public class CodeGenRefOutTests : CSharpTestBase { [Fact] public void TestOutParamSignature() { var source = @" class C { void M(out int x) { x = 0; } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M([out] System.Int32& x) cil managed") }); } [Fact] public void TestRefParamSignature() { var source = @" class C { void M(ref int x) { } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M(System.Int32& x) cil managed") }); } [Fact] public void TestOneReferenceMultipleParameters() { var source = @" class C { static void Main() { int z = 0; Test(ref z, out z); System.Console.WriteLine(z); } static void Test(ref int x, out int y) { x = 1; y = 2; } }"; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void TestReferenceParameterOrder() { var source = @" public class Test { static int[] array = new int[1]; public static void Main(string[] args) { // Named parameters are in reversed order // Arguments have side effects // Arguments refer to the same array element Goo(y: out GetArray(""A"")[GetIndex(""B"")], x: ref GetArray(""C"")[GetIndex(""D"")]); System.Console.WriteLine(array[0]); } static void Goo(ref int x, out int y) { x = 1; y = 2; } static int GetIndex(string msg) { System.Console.WriteLine(""Index {0}"", msg); return 0; } static int[] GetArray(string msg) { System.Console.WriteLine(""Array {0}"", msg); return array; } }"; CompileAndVerify(source, expectedOutput: @" Array A Index B Array C Index D 2"); } [Fact] public void TestPassMutableStructByReference() { var source = @" class C { static void Main() { MutableStruct s1 = new MutableStruct(); s1.Dump(); ByRef(ref s1, 2); s1.Dump(); System.Console.WriteLine(); MutableStruct s2 = new MutableStruct(); s2.Dump(); ByVal(s2, 2); s2.Dump(); } static void ByRef(ref MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByRef(ref s, depth - 1); s.Dump(); } } static void ByVal(MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByVal(s, depth - 1); s.Dump(); } } } struct MutableStruct { private bool flagged; public void Flag() { this.flagged = true; } public void Dump() { System.Console.WriteLine(flagged ? ""Flagged"" : ""Unflagged""); } }"; CompileAndVerify(source, expectedOutput: @" Unflagged Unflagged Unflagged Flagged Flagged Flagged Unflagged Unflagged Unflagged Unflagged Unflagged Unflagged"); } [Fact] public void TestPassFieldByReference() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestRef(ref c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestRef(ref c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestRef(ref C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestRef(ref C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestRef(ref int x) { x++; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [Fact] public void TestSetFieldViaOutParameter() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestOut(out c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestOut(out c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestOut(out C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestOut(out C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestOut(out int x) { x = 1; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [WorkItem(543521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543521")] [Fact()] public void TestConstructorWithOutParameter() { CompileAndVerify(@" class Class1 { Class1(out bool outParam) { outParam = true; } static void Main() { var b = false; var c1 = new Class1(out b); } }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void RefExtensionMethods_OutParam() { var code = @" using System; public class C { public static void Main() { var inst = new S1(); int orig; var result = inst.Mutate(out orig); System.Console.Write(orig); System.Console.Write(inst.x); } } public static class S1_Ex { public static bool Mutate(ref this S1 instance, out int orig) { orig = instance.x; instance.x = 42; return true; } } public struct S1 { public int x; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "042"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 2 .locals init (S1 V_0, //inst int V_1) //orig IL_0000: ldloca.s V_0 IL_0002: initobj ""S1"" IL_0008: ldloca.s V_0 IL_000a: ldloca.s V_1 IL_000c: call ""bool S1_Ex.Mutate(ref S1, out int)"" IL_0011: pop IL_0012: ldloc.1 IL_0013: call ""void System.Console.Write(int)"" IL_0018: ldloc.0 IL_0019: ldfld ""int S1.x"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptional() { var code = @" using System; public class C { public static C cc => new C(); readonly int x; readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var c = C.cc.Test(1, this, out x, out y); } public C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = 2; return arg2; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 34 (0x22) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: call ""C C.cc.get"" IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldarg.0 IL_0012: ldarga.s V_1 IL_0014: ldarg.0 IL_0015: ldflda ""int C.y"" IL_001a: ldnull IL_001b: callvirt ""C C.Test(object, C, out int, out int, object)"" IL_0020: pop IL_0021: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptionalNested() { var code = @" using System; public class C { public static C cc => new C(); readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var captured = 2; C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = captured++; return arg2; } var c = Test(1, this, out x, out y); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 39 (0x27) .maxstack 6 .locals init (C.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldloca.s V_0 IL_0008: ldc.i4.2 IL_0009: stfld ""int C.<>c__DisplayClass5_0.captured"" IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldarg.0 IL_0015: ldarga.s V_1 IL_0017: ldarg.0 IL_0018: ldflda ""int C.y"" IL_001d: ldnull IL_001e: ldloca.s V_0 IL_0020: call ""C C.<.ctor>g__Test|5_0(object, C, out int, out int, object, ref C.<>c__DisplayClass5_0)"" IL_0025: pop IL_0026: ret }"); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/LocalDeclarationStatementSyntax.cs
// Licensed to the .NET Foundation under one or more 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 LocalDeclarationStatementSyntax { public LocalDeclarationStatementSyntax Update(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => Update(AwaitKeyword, UsingKeyword, modifiers, declaration, semicolonToken); public LocalDeclarationStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => Update(AttributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => LocalDeclarationStatement(awaitKeyword: default, usingKeyword: default, modifiers, declaration, semicolonToken); public static LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => LocalDeclarationStatement(attributeLists: default, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); public static LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration) => LocalDeclarationStatement(attributeLists: default, modifiers, declaration); } }
// Licensed to the .NET Foundation under one or more 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 LocalDeclarationStatementSyntax { public LocalDeclarationStatementSyntax Update(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => Update(AwaitKeyword, UsingKeyword, modifiers, declaration, semicolonToken); public LocalDeclarationStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => Update(AttributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => LocalDeclarationStatement(awaitKeyword: default, usingKeyword: default, modifiers, declaration, semicolonToken); public static LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) => LocalDeclarationStatement(attributeLists: default, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); public static LocalDeclarationStatementSyntax LocalDeclarationStatement(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration) => LocalDeclarationStatement(attributeLists: default, modifiers, declaration); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Symbol/Symbols/MockSymbolTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Text; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolTests { [Fact] public void TestArrayType() { CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamedTypeSymbol elementType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. ArrayTypeSymbol ats1 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 1); Assert.Equal(1, ats1.Rank); Assert.True(ats1.IsSZArray); Assert.Same(elementType, ats1.ElementType); Assert.Equal(SymbolKind.ArrayType, ats1.Kind); Assert.True(ats1.IsReferenceType); Assert.False(ats1.IsValueType); Assert.Equal("TestClass[]", ats1.ToTestDisplayString()); ArrayTypeSymbol ats2 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 2); Assert.Equal(2, ats2.Rank); Assert.Same(elementType, ats2.ElementType); Assert.Equal(SymbolKind.ArrayType, ats2.Kind); Assert.True(ats2.IsReferenceType); Assert.False(ats2.IsValueType); Assert.Equal("TestClass[,]", ats2.ToTestDisplayString()); ArrayTypeSymbol ats3 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 3); Assert.Equal(3, ats3.Rank); Assert.Equal("TestClass[,,]", ats3.ToTestDisplayString()); } [Fact] public void TestPointerType() { NamedTypeSymbol pointedAtType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. PointerTypeSymbol pts1 = new PointerTypeSymbol(TypeWithAnnotations.Create(pointedAtType)); Assert.Same(pointedAtType, pts1.PointedAtType); Assert.Equal(SymbolKind.PointerType, pts1.Kind); Assert.False(pts1.IsReferenceType); Assert.True(pts1.IsValueType); Assert.Equal("TestClass*", pts1.ToTestDisplayString()); } [Fact] public void TestMissingMetadataSymbol() { AssemblyIdentity missingAssemblyId = new AssemblyIdentity("goo"); AssemblySymbol assem = new MockAssemblySymbol("banana"); ModuleSymbol module = new MissingModuleSymbol(assem, ordinal: -1); NamedTypeSymbol container = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>(), TypeKind.Class); var mms1 = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(missingAssemblyId).Modules[0], "Elvis", "Lives", 2, true); Assert.Equal(2, mms1.Arity); Assert.Equal("Elvis", mms1.NamespaceName); Assert.Equal("Lives", mms1.Name); Assert.Equal("Elvis.Lives<,>[missing]", mms1.ToTestDisplayString()); Assert.Equal("goo", mms1.ContainingAssembly.Identity.Name); var mms2 = new MissingMetadataTypeSymbol.TopLevel(module, "Elvis.Is", "Cool", 0, true); Assert.Equal(0, mms2.Arity); Assert.Equal("Elvis.Is", mms2.NamespaceName); Assert.Equal("Cool", mms2.Name); Assert.Equal("Elvis.Is.Cool[missing]", mms2.ToTestDisplayString()); Assert.Same(assem, mms2.ContainingAssembly); // TODO: Add test for 3rd constructor. } [Fact] public void TestNamespaceExtent() { AssemblySymbol assem1 = new MockAssemblySymbol("goo"); NamespaceExtent ne1 = new NamespaceExtent(assem1); Assert.Equal(NamespaceKind.Assembly, ne1.Kind); Assert.Same(ne1.Assembly, assem1); CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamespaceExtent ne2 = new NamespaceExtent(compilation); Assert.IsType<CSharpCompilation>(ne2.Compilation); Assert.Throws<InvalidOperationException>(() => ne1.Compilation); } private Symbol CreateMockSymbol(NamespaceExtent extent, XElement xel) { Symbol result; var childSymbols = from childElement in xel.Elements() select CreateMockSymbol(extent, childElement); string name = xel.Attribute("name").Value; switch (xel.Name.LocalName) { case "ns": result = new MockNamespaceSymbol(name, extent, childSymbols); break; case "class": result = new MockNamedTypeSymbol(name, childSymbols, TypeKind.Class); break; default: throw new InvalidOperationException("unexpected xml element"); } foreach (IMockSymbol child in childSymbols) { child.SetContainer(result); } return result; } private void DumpSymbol(Symbol sym, StringBuilder builder, int level) { if (sym is NamespaceSymbol) { builder.AppendFormat("namespace {0} [{1}]", sym.Name, (sym as NamespaceSymbol).Extent); } else if (sym is NamedTypeSymbol) { builder.AppendFormat("{0} {1}", (sym as NamedTypeSymbol).TypeKind.ToString().ToLower(), sym.Name); } else { throw new InvalidOperationException("Unexpected symbol kind"); } if (sym is NamespaceOrTypeSymbol namespaceOrType && namespaceOrType.GetMembers().Any()) { builder.AppendLine(" { "); var q = from c in namespaceOrType.GetMembers() orderby c.Name select c; foreach (Symbol child in q) { for (int i = 0; i <= level; ++i) { builder.Append(" "); } DumpSymbol(child, builder, level + 1); builder.AppendLine(); } for (int i = 0; i < level; ++i) { builder.Append(" "); } builder.Append("}"); } } private string DumpSymbol(Symbol sym) { StringBuilder builder = new StringBuilder(); DumpSymbol(sym, builder, 0); return builder.ToString(); } [Fact] public void TestMergedNamespaces() { NamespaceSymbol root1 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem1")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'/> <ns name='F'> <ns name='G'/> </ns> </ns> <ns name='B'/> <ns name='C'/> <ns name='U'/> <class name='X'/> </ns>")); NamespaceSymbol root2 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem2")), XElement.Parse( @"<ns name=''> <ns name='B'> <ns name='K'/> </ns> <ns name='C'/> <class name='X'/> <class name='Y'/> </ns>")); NamespaceSymbol root3 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem3")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'> <ns name='H'/> </ns> </ns> <ns name='B'> <ns name='K'> <ns name='L'/> <class name='L'/> </ns> </ns> <class name='Z'/> </ns>")); NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, new NamespaceSymbol[] { root1, root2, root3 }.AsImmutable()); string expected = @"namespace [Assembly: Merged] { namespace A [Assembly: Merged] { namespace D [Assembly: Merged] namespace E [Assembly: Merged] { namespace H [Assembly: Assem3] } namespace F [Assembly: Assem1] { namespace G [Assembly: Assem1] } } namespace B [Assembly: Merged] { namespace K [Assembly: Merged] { class L namespace L [Assembly: Assem3] } } namespace C [Assembly: Merged] namespace U [Assembly: Assem1] class X class X class Y class Z }".Replace("Assembly: Merged", "Assembly: Merged, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem1", "Assembly: Assem1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem3", "Assembly: Assem3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); Assert.Equal(expected, DumpSymbol(merged)); NamespaceSymbol merged2 = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged2")), null, new NamespaceSymbol[] { root1 }.AsImmutable()); Assert.Same(merged2, root1); } } internal interface IMockSymbol { void SetContainer(Symbol container); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Text; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolTests { [Fact] public void TestArrayType() { CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamedTypeSymbol elementType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. ArrayTypeSymbol ats1 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 1); Assert.Equal(1, ats1.Rank); Assert.True(ats1.IsSZArray); Assert.Same(elementType, ats1.ElementType); Assert.Equal(SymbolKind.ArrayType, ats1.Kind); Assert.True(ats1.IsReferenceType); Assert.False(ats1.IsValueType); Assert.Equal("TestClass[]", ats1.ToTestDisplayString()); ArrayTypeSymbol ats2 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 2); Assert.Equal(2, ats2.Rank); Assert.Same(elementType, ats2.ElementType); Assert.Equal(SymbolKind.ArrayType, ats2.Kind); Assert.True(ats2.IsReferenceType); Assert.False(ats2.IsValueType); Assert.Equal("TestClass[,]", ats2.ToTestDisplayString()); ArrayTypeSymbol ats3 = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(elementType), rank: 3); Assert.Equal(3, ats3.Rank); Assert.Equal("TestClass[,,]", ats3.ToTestDisplayString()); } [Fact] public void TestPointerType() { NamedTypeSymbol pointedAtType = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>()); // this can be any type. PointerTypeSymbol pts1 = new PointerTypeSymbol(TypeWithAnnotations.Create(pointedAtType)); Assert.Same(pointedAtType, pts1.PointedAtType); Assert.Equal(SymbolKind.PointerType, pts1.Kind); Assert.False(pts1.IsReferenceType); Assert.True(pts1.IsValueType); Assert.Equal("TestClass*", pts1.ToTestDisplayString()); } [Fact] public void TestMissingMetadataSymbol() { AssemblyIdentity missingAssemblyId = new AssemblyIdentity("goo"); AssemblySymbol assem = new MockAssemblySymbol("banana"); ModuleSymbol module = new MissingModuleSymbol(assem, ordinal: -1); NamedTypeSymbol container = new MockNamedTypeSymbol("TestClass", Enumerable.Empty<Symbol>(), TypeKind.Class); var mms1 = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(missingAssemblyId).Modules[0], "Elvis", "Lives", 2, true); Assert.Equal(2, mms1.Arity); Assert.Equal("Elvis", mms1.NamespaceName); Assert.Equal("Lives", mms1.Name); Assert.Equal("Elvis.Lives<,>[missing]", mms1.ToTestDisplayString()); Assert.Equal("goo", mms1.ContainingAssembly.Identity.Name); var mms2 = new MissingMetadataTypeSymbol.TopLevel(module, "Elvis.Is", "Cool", 0, true); Assert.Equal(0, mms2.Arity); Assert.Equal("Elvis.Is", mms2.NamespaceName); Assert.Equal("Cool", mms2.Name); Assert.Equal("Elvis.Is.Cool[missing]", mms2.ToTestDisplayString()); Assert.Same(assem, mms2.ContainingAssembly); // TODO: Add test for 3rd constructor. } [Fact] public void TestNamespaceExtent() { AssemblySymbol assem1 = new MockAssemblySymbol("goo"); NamespaceExtent ne1 = new NamespaceExtent(assem1); Assert.Equal(NamespaceKind.Assembly, ne1.Kind); Assert.Same(ne1.Assembly, assem1); CSharpCompilation compilation = CSharpCompilation.Create("Test"); NamespaceExtent ne2 = new NamespaceExtent(compilation); Assert.IsType<CSharpCompilation>(ne2.Compilation); Assert.Throws<InvalidOperationException>(() => ne1.Compilation); } private Symbol CreateMockSymbol(NamespaceExtent extent, XElement xel) { Symbol result; var childSymbols = from childElement in xel.Elements() select CreateMockSymbol(extent, childElement); string name = xel.Attribute("name").Value; switch (xel.Name.LocalName) { case "ns": result = new MockNamespaceSymbol(name, extent, childSymbols); break; case "class": result = new MockNamedTypeSymbol(name, childSymbols, TypeKind.Class); break; default: throw new InvalidOperationException("unexpected xml element"); } foreach (IMockSymbol child in childSymbols) { child.SetContainer(result); } return result; } private void DumpSymbol(Symbol sym, StringBuilder builder, int level) { if (sym is NamespaceSymbol) { builder.AppendFormat("namespace {0} [{1}]", sym.Name, (sym as NamespaceSymbol).Extent); } else if (sym is NamedTypeSymbol) { builder.AppendFormat("{0} {1}", (sym as NamedTypeSymbol).TypeKind.ToString().ToLower(), sym.Name); } else { throw new InvalidOperationException("Unexpected symbol kind"); } if (sym is NamespaceOrTypeSymbol namespaceOrType && namespaceOrType.GetMembers().Any()) { builder.AppendLine(" { "); var q = from c in namespaceOrType.GetMembers() orderby c.Name select c; foreach (Symbol child in q) { for (int i = 0; i <= level; ++i) { builder.Append(" "); } DumpSymbol(child, builder, level + 1); builder.AppendLine(); } for (int i = 0; i < level; ++i) { builder.Append(" "); } builder.Append("}"); } } private string DumpSymbol(Symbol sym) { StringBuilder builder = new StringBuilder(); DumpSymbol(sym, builder, 0); return builder.ToString(); } [Fact] public void TestMergedNamespaces() { NamespaceSymbol root1 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem1")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'/> <ns name='F'> <ns name='G'/> </ns> </ns> <ns name='B'/> <ns name='C'/> <ns name='U'/> <class name='X'/> </ns>")); NamespaceSymbol root2 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem2")), XElement.Parse( @"<ns name=''> <ns name='B'> <ns name='K'/> </ns> <ns name='C'/> <class name='X'/> <class name='Y'/> </ns>")); NamespaceSymbol root3 = (NamespaceSymbol)CreateMockSymbol(new NamespaceExtent(new MockAssemblySymbol("Assem3")), XElement.Parse( @"<ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'> <ns name='H'/> </ns> </ns> <ns name='B'> <ns name='K'> <ns name='L'/> <class name='L'/> </ns> </ns> <class name='Z'/> </ns>")); NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, new NamespaceSymbol[] { root1, root2, root3 }.AsImmutable()); string expected = @"namespace [Assembly: Merged] { namespace A [Assembly: Merged] { namespace D [Assembly: Merged] namespace E [Assembly: Merged] { namespace H [Assembly: Assem3] } namespace F [Assembly: Assem1] { namespace G [Assembly: Assem1] } } namespace B [Assembly: Merged] { namespace K [Assembly: Merged] { class L namespace L [Assembly: Assem3] } } namespace C [Assembly: Merged] namespace U [Assembly: Assem1] class X class X class Y class Z }".Replace("Assembly: Merged", "Assembly: Merged, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem1", "Assembly: Assem1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") .Replace("Assembly: Assem3", "Assembly: Assem3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); Assert.Equal(expected, DumpSymbol(merged)); NamespaceSymbol merged2 = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged2")), null, new NamespaceSymbol[] { root1 }.AsImmutable()); Assert.Same(merged2, root1); } } internal interface IMockSymbol { void SetContainer(Symbol container); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/NavigationBar/NavigationBarControllerFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { [Export(typeof(INavigationBarControllerFactoryService))] internal class NavigationBarControllerFactoryService : INavigationBarControllerFactoryService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uIThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarControllerFactoryService( IThreadingContext threadingContext, IUIThreadOperationExecutor uIThreadOperationExecutor, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uIThreadOperationExecutor = uIThreadOperationExecutor; _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigationBar); } public IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer) { return new NavigationBarController( _threadingContext, presenter, textBuffer, _uIThreadOperationExecutor, _asyncListener); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { [Export(typeof(INavigationBarControllerFactoryService))] internal class NavigationBarControllerFactoryService : INavigationBarControllerFactoryService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uIThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarControllerFactoryService( IThreadingContext threadingContext, IUIThreadOperationExecutor uIThreadOperationExecutor, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uIThreadOperationExecutor = uIThreadOperationExecutor; _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigationBar); } public IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer) { return new NavigationBarController( _threadingContext, presenter, textBuffer, _uIThreadOperationExecutor, _asyncListener); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/SettingsProviderBase.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using static Microsoft.CodeAnalysis.ProjectState; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal abstract class SettingsProviderBase<TData, TOptionsUpdater, TOption, TValue> : ISettingsProvider<TData> where TOptionsUpdater : ISettingUpdater<TOption, TValue> { private readonly List<TData> _snapshot = new(); private static readonly object s_gate = new(); private ISettingsEditorViewModel? _viewModel; protected readonly string FileName; protected readonly TOptionsUpdater SettingsUpdater; protected readonly Workspace Workspace; protected abstract void UpdateOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions); protected SettingsProviderBase(string fileName, TOptionsUpdater settingsUpdater, Workspace workspace) { FileName = fileName; SettingsUpdater = settingsUpdater; Workspace = workspace; } protected void Update() { var givenFolder = new DirectoryInfo(FileName).Parent; var solution = Workspace.CurrentSolution; var projects = solution.GetProjectsForPath(FileName); var project = projects.FirstOrDefault(); if (project is null) { // no .NET projects in the solution return; } var configOptionsProvider = new WorkspaceAnalyzerConfigOptionsProvider(project.State); var workspaceOptions = configOptionsProvider.GetOptionsForSourcePath(givenFolder.FullName); var result = project.GetAnalyzerConfigOptions(); var options = new CombinedAnalyzerConfigOptions(workspaceOptions, result); UpdateOptions(options, Workspace.Options); } public async Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText) { if (!await SettingsUpdater.HasAnyChangesAsync().ConfigureAwait(false)) { return sourceText; } var text = await SettingsUpdater.GetChangedEditorConfigAsync(sourceText, default).ConfigureAwait(false); return text is not null ? text : sourceText; } public ImmutableArray<TData> GetCurrentDataSnapshot() { lock (s_gate) { return _snapshot.ToImmutableArray(); } } protected void AddRange(IEnumerable<TData> items) { lock (s_gate) { _snapshot.AddRange(items); } _viewModel?.NotifyOfUpdate(); } public void RegisterViewModel(ISettingsEditorViewModel viewModel) => _viewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); private sealed class CombinedAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly AnalyzerConfigOptions _workspaceOptions; private readonly AnalyzerConfigOptionsResult? _result; public CombinedAnalyzerConfigOptions(AnalyzerConfigOptions workspaceOptions, AnalyzerConfigOptionsResult? result) { _workspaceOptions = workspaceOptions; _result = result; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { if (_workspaceOptions.TryGetValue(key, out value)) { return true; } if (!_result.HasValue) { value = null; return false; } if (_result.Value.AnalyzerOptions.TryGetValue(key, out value)) { return true; } var diagnosticKey = "dotnet_diagnostic.(?<key>.*).severity"; var match = Regex.Match(key, diagnosticKey); if (match.Success && match.Groups["key"].Value is string isolatedKey && _result.Value.TreeOptions.TryGetValue(isolatedKey, out var severity)) { value = severity.ToEditorConfigString(); return true; } value = 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using static Microsoft.CodeAnalysis.ProjectState; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal abstract class SettingsProviderBase<TData, TOptionsUpdater, TOption, TValue> : ISettingsProvider<TData> where TOptionsUpdater : ISettingUpdater<TOption, TValue> { private readonly List<TData> _snapshot = new(); private static readonly object s_gate = new(); private ISettingsEditorViewModel? _viewModel; protected readonly string FileName; protected readonly TOptionsUpdater SettingsUpdater; protected readonly Workspace Workspace; protected abstract void UpdateOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions); protected SettingsProviderBase(string fileName, TOptionsUpdater settingsUpdater, Workspace workspace) { FileName = fileName; SettingsUpdater = settingsUpdater; Workspace = workspace; } protected void Update() { var givenFolder = new DirectoryInfo(FileName).Parent; var solution = Workspace.CurrentSolution; var projects = solution.GetProjectsForPath(FileName); var project = projects.FirstOrDefault(); if (project is null) { // no .NET projects in the solution return; } var configOptionsProvider = new WorkspaceAnalyzerConfigOptionsProvider(project.State); var workspaceOptions = configOptionsProvider.GetOptionsForSourcePath(givenFolder.FullName); var result = project.GetAnalyzerConfigOptions(); var options = new CombinedAnalyzerConfigOptions(workspaceOptions, result); UpdateOptions(options, Workspace.Options); } public async Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText) { if (!await SettingsUpdater.HasAnyChangesAsync().ConfigureAwait(false)) { return sourceText; } var text = await SettingsUpdater.GetChangedEditorConfigAsync(sourceText, default).ConfigureAwait(false); return text is not null ? text : sourceText; } public ImmutableArray<TData> GetCurrentDataSnapshot() { lock (s_gate) { return _snapshot.ToImmutableArray(); } } protected void AddRange(IEnumerable<TData> items) { lock (s_gate) { _snapshot.AddRange(items); } _viewModel?.NotifyOfUpdate(); } public void RegisterViewModel(ISettingsEditorViewModel viewModel) => _viewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); private sealed class CombinedAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly AnalyzerConfigOptions _workspaceOptions; private readonly AnalyzerConfigOptionsResult? _result; public CombinedAnalyzerConfigOptions(AnalyzerConfigOptions workspaceOptions, AnalyzerConfigOptionsResult? result) { _workspaceOptions = workspaceOptions; _result = result; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { if (_workspaceOptions.TryGetValue(key, out value)) { return true; } if (!_result.HasValue) { value = null; return false; } if (_result.Value.AnalyzerOptions.TryGetValue(key, out value)) { return true; } var diagnosticKey = "dotnet_diagnostic.(?<key>.*).severity"; var match = Regex.Match(key, diagnosticKey); if (match.Success && match.Groups["key"].Value is string isolatedKey && _result.Value.TreeOptions.TryGetValue(isolatedKey, out var severity)) { value = severity.ToEditorConfigString(); return true; } value = null; return false; } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Tagging/TaggerContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal class TaggerContext<TTag> where TTag : ITag { private readonly ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _existingTags; internal IEnumerable<DocumentSnapshotSpan> _spansTagged; internal ImmutableArray<ITagSpan<TTag>>.Builder tagSpans = ImmutableArray.CreateBuilder<ITagSpan<TTag>>(); public ImmutableArray<DocumentSnapshotSpan> SpansToTag { get; } public SnapshotPoint? CaretPosition { get; } /// <summary> /// The text that has changed between the last successful tagging and this new request to /// produce tags. In order to be passed this value, <see cref="TaggerTextChangeBehavior.TrackTextChanges"/> /// must be specified in <see cref="AbstractAsynchronousTaggerProvider{TTag}.TextChangeBehavior"/>. /// </summary> public TextChangeRange? TextChangeRange { get; } public CancellationToken CancellationToken { get; } /// <summary> /// The state of the tagger. Taggers can use this to keep track of information across calls /// to <see cref="AbstractAsynchronousTaggerProvider{TTag}.ProduceTagsAsync(TaggerContext{TTag})"/>. Note: state will /// only be preserved if the tagger infrastructure fully updates itself with the tags that /// were produced. i.e. if that tagging pass is canceled, then the state set here will not /// be preserved and the previous preserved state will be used the next time ProduceTagsAsync /// is called. /// </summary> public object State { get; set; } // For testing only. internal TaggerContext( Document document, ITextSnapshot snapshot, SnapshotPoint? caretPosition = null, TextChangeRange? textChangeRange = null, CancellationToken cancellationToken = default) : this(state: null, ImmutableArray.Create(new DocumentSnapshotSpan(document, snapshot.GetFullSpan())), caretPosition, textChangeRange, existingTags: null, cancellationToken) { } internal TaggerContext( object state, ImmutableArray<DocumentSnapshotSpan> spansToTag, SnapshotPoint? caretPosition, TextChangeRange? textChangeRange, ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> existingTags, CancellationToken cancellationToken) { this.State = state; this.SpansToTag = spansToTag; this.CaretPosition = caretPosition; this.TextChangeRange = textChangeRange; this.CancellationToken = cancellationToken; _spansTagged = spansToTag; _existingTags = existingTags; } public void AddTag(ITagSpan<TTag> tag) => tagSpans.Add(tag); public void ClearTags() => tagSpans.Clear(); /// <summary> /// Used to allow taggers to indicate what spans were actually tagged. This is useful /// when the tagger decides to tag a different span than the entire file. If a sub-span /// of a document is tagged then the tagger infrastructure will keep previously computed /// tags from before and after the sub-span and merge them with the newly produced tags. /// </summary> public void SetSpansTagged(IEnumerable<DocumentSnapshotSpan> spansTagged) => this._spansTagged = spansTagged ?? throw new ArgumentNullException(nameof(spansTagged)); public IEnumerable<ITagSpan<TTag>> GetExistingContainingTags(SnapshotPoint point) { if (_existingTags != null && _existingTags.TryGetValue(point.Snapshot.TextBuffer, out var tree)) { return tree.GetIntersectingSpans(new SnapshotSpan(point.Snapshot, new Span(point, 0))) .Where(s => s.Span.Contains(point)); } return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal class TaggerContext<TTag> where TTag : ITag { private readonly ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _existingTags; internal IEnumerable<DocumentSnapshotSpan> _spansTagged; internal ImmutableArray<ITagSpan<TTag>>.Builder tagSpans = ImmutableArray.CreateBuilder<ITagSpan<TTag>>(); public ImmutableArray<DocumentSnapshotSpan> SpansToTag { get; } public SnapshotPoint? CaretPosition { get; } /// <summary> /// The text that has changed between the last successful tagging and this new request to /// produce tags. In order to be passed this value, <see cref="TaggerTextChangeBehavior.TrackTextChanges"/> /// must be specified in <see cref="AbstractAsynchronousTaggerProvider{TTag}.TextChangeBehavior"/>. /// </summary> public TextChangeRange? TextChangeRange { get; } public CancellationToken CancellationToken { get; } /// <summary> /// The state of the tagger. Taggers can use this to keep track of information across calls /// to <see cref="AbstractAsynchronousTaggerProvider{TTag}.ProduceTagsAsync(TaggerContext{TTag})"/>. Note: state will /// only be preserved if the tagger infrastructure fully updates itself with the tags that /// were produced. i.e. if that tagging pass is canceled, then the state set here will not /// be preserved and the previous preserved state will be used the next time ProduceTagsAsync /// is called. /// </summary> public object State { get; set; } // For testing only. internal TaggerContext( Document document, ITextSnapshot snapshot, SnapshotPoint? caretPosition = null, TextChangeRange? textChangeRange = null, CancellationToken cancellationToken = default) : this(state: null, ImmutableArray.Create(new DocumentSnapshotSpan(document, snapshot.GetFullSpan())), caretPosition, textChangeRange, existingTags: null, cancellationToken) { } internal TaggerContext( object state, ImmutableArray<DocumentSnapshotSpan> spansToTag, SnapshotPoint? caretPosition, TextChangeRange? textChangeRange, ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> existingTags, CancellationToken cancellationToken) { this.State = state; this.SpansToTag = spansToTag; this.CaretPosition = caretPosition; this.TextChangeRange = textChangeRange; this.CancellationToken = cancellationToken; _spansTagged = spansToTag; _existingTags = existingTags; } public void AddTag(ITagSpan<TTag> tag) => tagSpans.Add(tag); public void ClearTags() => tagSpans.Clear(); /// <summary> /// Used to allow taggers to indicate what spans were actually tagged. This is useful /// when the tagger decides to tag a different span than the entire file. If a sub-span /// of a document is tagged then the tagger infrastructure will keep previously computed /// tags from before and after the sub-span and merge them with the newly produced tags. /// </summary> public void SetSpansTagged(IEnumerable<DocumentSnapshotSpan> spansTagged) => this._spansTagged = spansTagged ?? throw new ArgumentNullException(nameof(spansTagged)); public IEnumerable<ITagSpan<TTag>> GetExistingContainingTags(SnapshotPoint point) { if (_existingTags != null && _existingTags.TryGetValue(point.Snapshot.TextBuffer, out var tree)) { return tree.GetIntersectingSpans(new SnapshotSpan(point.Snapshot, new Span(point, 0))) .Where(s => s.Span.Contains(point)); } return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Synthesized/GeneratedLabelSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class GeneratedLabelSymbol : LabelSymbol { private readonly string _name; public GeneratedLabelSymbol(string name) { _name = LabelName(name); #if DEBUG NameNoSequence = $"<{name}>"; #endif } public override string Name { get { return _name; } } #if DEBUG internal string NameNoSequence { get; } private static int s_sequence = 1; #endif private static string LabelName(string name) { #if DEBUG int seq = System.Threading.Interlocked.Add(ref s_sequence, 1); return "<" + name + "-" + (seq & 0xffff) + ">"; #else return name; #endif } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override bool IsImplicitlyDeclared { get { 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.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class GeneratedLabelSymbol : LabelSymbol { private readonly string _name; public GeneratedLabelSymbol(string name) { _name = LabelName(name); #if DEBUG NameNoSequence = $"<{name}>"; #endif } public override string Name { get { return _name; } } #if DEBUG internal string NameNoSequence { get; } private static int s_sequence = 1; #endif private static string LabelName(string name) { #if DEBUG int seq = System.Threading.Interlocked.Add(ref s_sequence, 1); return "<" + name + "-" + (seq & 0xffff) + ">"; #else return name; #endif } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override bool IsImplicitlyDeclared { get { return true; } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_DoStatement.cs
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitDoStatement(BoundDoStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); var startLabel = new GeneratedLabelSymbol("start"); var syntax = node.Syntax; // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (!node.WasCompilerGenerated && this.Instrument) { rewrittenCondition = _instrumenter.InstrumentDoStatementCondition(node, rewrittenCondition, _factory); } BoundStatement ifConditionGotoStart = new BoundConditionalGoto(syntax, rewrittenCondition, true, startLabel); if (!node.WasCompilerGenerated && this.Instrument) { ifConditionGotoStart = _instrumenter.InstrumentDoStatementConditionalGotoStart(node, ifConditionGotoStart); } // do // body // while (condition); // // becomes // // start: // { // body // continue: // sequence point // GotoIfTrue condition start; // } // break: if (node.Locals.IsEmpty) { return BoundStatementList.Synthesized(syntax, node.HasErrors, new BoundLabelStatement(syntax, startLabel), rewrittenBody, new BoundLabelStatement(syntax, node.ContinueLabel), ifConditionGotoStart, new BoundLabelStatement(syntax, node.BreakLabel)); } return BoundStatementList.Synthesized(syntax, node.HasErrors, new BoundLabelStatement(syntax, startLabel), new BoundBlock(syntax, node.Locals, ImmutableArray.Create<BoundStatement>(rewrittenBody, new BoundLabelStatement(syntax, node.ContinueLabel), ifConditionGotoStart)), new BoundLabelStatement(syntax, node.BreakLabel)); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitDoStatement(BoundDoStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); var startLabel = new GeneratedLabelSymbol("start"); var syntax = node.Syntax; // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (!node.WasCompilerGenerated && this.Instrument) { rewrittenCondition = _instrumenter.InstrumentDoStatementCondition(node, rewrittenCondition, _factory); } BoundStatement ifConditionGotoStart = new BoundConditionalGoto(syntax, rewrittenCondition, true, startLabel); if (!node.WasCompilerGenerated && this.Instrument) { ifConditionGotoStart = _instrumenter.InstrumentDoStatementConditionalGotoStart(node, ifConditionGotoStart); } // do // body // while (condition); // // becomes // // start: // { // body // continue: // sequence point // GotoIfTrue condition start; // } // break: if (node.Locals.IsEmpty) { return BoundStatementList.Synthesized(syntax, node.HasErrors, new BoundLabelStatement(syntax, startLabel), rewrittenBody, new BoundLabelStatement(syntax, node.ContinueLabel), ifConditionGotoStart, new BoundLabelStatement(syntax, node.BreakLabel)); } return BoundStatementList.Synthesized(syntax, node.HasErrors, new BoundLabelStatement(syntax, startLabel), new BoundBlock(syntax, node.Locals, ImmutableArray.Create<BoundStatement>(rewrittenBody, new BoundLabelStatement(syntax, node.ContinueLabel), ifConditionGotoStart)), new BoundLabelStatement(syntax, node.BreakLabel)); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectShim.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { /// <summary> /// The representation of a project to both the project factory and workspace API. /// </summary> /// <remarks> /// Due to the number of interfaces this object must implement, all interface implementations /// are in a separate files. Methods that are shared across multiple interfaces (which are /// effectively methods that just QI from one interface to another), are implemented here. /// </remarks> internal sealed partial class CSharpProjectShim : AbstractLegacyProject, ICodeModelInstanceFactory { /// <summary> /// This member is used to store a raw array of warning numbers, which is needed to properly implement /// ICSCompilerConfig.GetWarnNumbers. Read the implementation of that function for more details. /// </summary> private readonly IntPtr _warningNumberArrayPointer; private ICSharpProjectRoot _projectRoot; private readonly IServiceProvider _serviceProvider; /// <summary> /// Fetches the options processor for this C# project. Equivalent to the underlying member, but fixed to the derived type. /// </summary> private new OptionsProcessor VisualStudioProjectOptionsProcessor { get => (OptionsProcessor)base.VisualStudioProjectOptionsProcessor; set => base.VisualStudioProjectOptionsProcessor = value; } public CSharpProjectShim( ICSharpProjectRoot projectRoot, string projectSystemName, IVsHierarchy hierarchy, IServiceProvider serviceProvider, IThreadingContext threadingContext) : base(projectSystemName, hierarchy, LanguageNames.CSharp, isVsIntellisenseProject: projectRoot is IVsIntellisenseProject, serviceProvider, threadingContext, externalErrorReportingPrefix: "CS") { _projectRoot = projectRoot; _serviceProvider = serviceProvider; _warningNumberArrayPointer = Marshal.AllocHGlobal(0); var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); this.ProjectCodeModel = componentModel.GetService<IProjectCodeModelFactory>().CreateProjectCodeModel(VisualStudioProject.Id, this); this.VisualStudioProjectOptionsProcessor = new OptionsProcessor(this.VisualStudioProject, Workspace.Services); // Ensure the default options are set up ResetAllOptions(); } public override void Disconnect() { _projectRoot = null; base.Disconnect(); } ~CSharpProjectShim() { // Free the unmanaged memory we allocated in the constructor Marshal.FreeHGlobal(_warningNumberArrayPointer); // Free any entry point strings. if (_startupClasses != null) { foreach (var @class in _startupClasses) { Marshal.FreeHGlobal(@class); } } } EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath) { if (_projectRoot.CanCreateFileCodeModel(filePath)) { var iid = VSConstants.IID_IUnknown; return _projectRoot.CreateFileCodeModel(filePath, ref iid) as EnvDTE.FileCodeModel; } else { 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { /// <summary> /// The representation of a project to both the project factory and workspace API. /// </summary> /// <remarks> /// Due to the number of interfaces this object must implement, all interface implementations /// are in a separate files. Methods that are shared across multiple interfaces (which are /// effectively methods that just QI from one interface to another), are implemented here. /// </remarks> internal sealed partial class CSharpProjectShim : AbstractLegacyProject, ICodeModelInstanceFactory { /// <summary> /// This member is used to store a raw array of warning numbers, which is needed to properly implement /// ICSCompilerConfig.GetWarnNumbers. Read the implementation of that function for more details. /// </summary> private readonly IntPtr _warningNumberArrayPointer; private ICSharpProjectRoot _projectRoot; private readonly IServiceProvider _serviceProvider; /// <summary> /// Fetches the options processor for this C# project. Equivalent to the underlying member, but fixed to the derived type. /// </summary> private new OptionsProcessor VisualStudioProjectOptionsProcessor { get => (OptionsProcessor)base.VisualStudioProjectOptionsProcessor; set => base.VisualStudioProjectOptionsProcessor = value; } public CSharpProjectShim( ICSharpProjectRoot projectRoot, string projectSystemName, IVsHierarchy hierarchy, IServiceProvider serviceProvider, IThreadingContext threadingContext) : base(projectSystemName, hierarchy, LanguageNames.CSharp, isVsIntellisenseProject: projectRoot is IVsIntellisenseProject, serviceProvider, threadingContext, externalErrorReportingPrefix: "CS") { _projectRoot = projectRoot; _serviceProvider = serviceProvider; _warningNumberArrayPointer = Marshal.AllocHGlobal(0); var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); this.ProjectCodeModel = componentModel.GetService<IProjectCodeModelFactory>().CreateProjectCodeModel(VisualStudioProject.Id, this); this.VisualStudioProjectOptionsProcessor = new OptionsProcessor(this.VisualStudioProject, Workspace.Services); // Ensure the default options are set up ResetAllOptions(); } public override void Disconnect() { _projectRoot = null; base.Disconnect(); } ~CSharpProjectShim() { // Free the unmanaged memory we allocated in the constructor Marshal.FreeHGlobal(_warningNumberArrayPointer); // Free any entry point strings. if (_startupClasses != null) { foreach (var @class in _startupClasses) { Marshal.FreeHGlobal(@class); } } } EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath) { if (_projectRoot.CanCreateFileCodeModel(filePath)) { var iid = VSConstants.IID_IUnknown; return _projectRoot.CreateFileCodeModel(filePath, ref iid) as EnvDTE.FileCodeModel; } else { return null; } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Indentation/CSharpSmartTokenFormatter.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Indentation { internal class CSharpSmartTokenFormatter : ISmartTokenFormatter { private readonly OptionSet _optionSet; private readonly IEnumerable<AbstractFormattingRule> _formattingRules; private readonly CompilationUnitSyntax _root; public CSharpSmartTokenFormatter( OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, CompilationUnitSyntax root) { Contract.ThrowIfNull(optionSet); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(root); _optionSet = optionSet; _formattingRules = formattingRules; _root = root; } public IList<TextChange> FormatRange( Workspace workspace, SyntaxToken startToken, SyntaxToken endToken, CancellationToken cancellationToken) { Contract.ThrowIfTrue(startToken.Kind() == SyntaxKind.None || startToken.Kind() == SyntaxKind.EndOfFileToken); Contract.ThrowIfTrue(endToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.EndOfFileToken); var smartTokenformattingRules = _formattingRules; var common = startToken.GetCommonRoot(endToken); RoslynDebug.AssertNotNull(common); // if there are errors, do not touch lines // Exception 1: In the case of try-catch-finally block, a try block without a catch/finally block is considered incomplete // but we would like to apply line operation in a completed try block even if there is no catch/finally block // Exception 2: Similar behavior for do-while if (common.ContainsDiagnostics && !CloseBraceOfTryOrDoBlock(endToken)) { smartTokenformattingRules = (new NoLineChangeFormattingRule()).Concat(_formattingRules); } return Formatter.GetFormattedTextChanges(_root, new TextSpan[] { TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) }, workspace, _optionSet, smartTokenformattingRules, cancellationToken); } private static bool CloseBraceOfTryOrDoBlock(SyntaxToken endToken) { return endToken.IsKind(SyntaxKind.CloseBraceToken) && endToken.Parent.IsKind(SyntaxKind.Block) && (endToken.Parent.IsParentKind(SyntaxKind.TryStatement) || endToken.Parent.IsParentKind(SyntaxKind.DoStatement)); } public async Task<IList<TextChange>> FormatTokenAsync( Workspace workspace, SyntaxToken token, CancellationToken cancellationToken) { Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None || token.Kind() == SyntaxKind.EndOfFileToken); // get previous token var previousToken = token.GetPreviousToken(includeZeroWidth: true); if (previousToken.Kind() == SyntaxKind.None) { // no previous token. nothing to format return SpecializedCollections.EmptyList<TextChange>(); } // This is a heuristic to prevent brace completion from breaking user expectation/muscle memory in common scenarios (see Devdiv:823958). // Formatter uses FindToken on the position, which returns token to left, if there is nothing to the right and returns token to the right // if there exists one. If the shape is "{|}", we're including '}' in the formatting range. Avoid doing that to improve verbatim typing // in the following special scenarios. var adjustedEndPosition = token.Span.End; if (token.IsKind(SyntaxKind.OpenBraceToken) && (token.Parent.IsInitializerForArrayOrCollectionCreationExpression() || token.Parent is AnonymousObjectCreationExpressionSyntax)) { var nextToken = token.GetNextToken(includeZeroWidth: true); if (nextToken.IsKind(SyntaxKind.CloseBraceToken)) { // Format upto '{' and exclude '}' adjustedEndPosition = token.SpanStart; } } var smartTokenformattingRules = (new SmartTokenFormattingRule()).Concat(_formattingRules); var adjustedStartPosition = previousToken.SpanStart; var indentStyle = _optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp); if (token.IsKind(SyntaxKind.OpenBraceToken) && indentStyle != FormattingOptions.IndentStyle.Smart) { RoslynDebug.AssertNotNull(token.SyntaxTree); var text = await token.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); if (token.IsFirstTokenOnLine(text)) { adjustedStartPosition = token.SpanStart; } } return Formatter.GetFormattedTextChanges(_root, new TextSpan[] { TextSpan.FromBounds(adjustedStartPosition, adjustedEndPosition) }, workspace, _optionSet, smartTokenformattingRules, cancellationToken); } private class NoLineChangeFormattingRule : AbstractFormattingRule { public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { // no line operation. no line changes what so ever var lineOperation = base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); if (lineOperation != null) { // ignore force if same line option if (lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine) { return null; } // basically means don't ever put new line if there isn't already one, but do // indentation. return FormattingOperations.CreateAdjustNewLinesOperation(line: 0, option: AdjustNewLinesOption.PreserveLines); } return null; } } private class SmartTokenFormattingRule : NoLineChangeFormattingRule { public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) { // don't suppress anything } public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { var spaceOperation = base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); // if there is force space operation, convert it to ForceSpaceIfSingleLine operation. // (force space basically means remove all line breaks) if (spaceOperation != null && spaceOperation.Option == AdjustSpacesOption.ForceSpaces) { return FormattingOperations.CreateAdjustSpacesOperation(spaceOperation.Space, AdjustSpacesOption.ForceSpacesIfOnSingleLine); } return spaceOperation; } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Indentation { internal class CSharpSmartTokenFormatter : ISmartTokenFormatter { private readonly OptionSet _optionSet; private readonly IEnumerable<AbstractFormattingRule> _formattingRules; private readonly CompilationUnitSyntax _root; public CSharpSmartTokenFormatter( OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, CompilationUnitSyntax root) { Contract.ThrowIfNull(optionSet); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(root); _optionSet = optionSet; _formattingRules = formattingRules; _root = root; } public IList<TextChange> FormatRange( Workspace workspace, SyntaxToken startToken, SyntaxToken endToken, CancellationToken cancellationToken) { Contract.ThrowIfTrue(startToken.Kind() == SyntaxKind.None || startToken.Kind() == SyntaxKind.EndOfFileToken); Contract.ThrowIfTrue(endToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.EndOfFileToken); var smartTokenformattingRules = _formattingRules; var common = startToken.GetCommonRoot(endToken); RoslynDebug.AssertNotNull(common); // if there are errors, do not touch lines // Exception 1: In the case of try-catch-finally block, a try block without a catch/finally block is considered incomplete // but we would like to apply line operation in a completed try block even if there is no catch/finally block // Exception 2: Similar behavior for do-while if (common.ContainsDiagnostics && !CloseBraceOfTryOrDoBlock(endToken)) { smartTokenformattingRules = (new NoLineChangeFormattingRule()).Concat(_formattingRules); } return Formatter.GetFormattedTextChanges(_root, new TextSpan[] { TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) }, workspace, _optionSet, smartTokenformattingRules, cancellationToken); } private static bool CloseBraceOfTryOrDoBlock(SyntaxToken endToken) { return endToken.IsKind(SyntaxKind.CloseBraceToken) && endToken.Parent.IsKind(SyntaxKind.Block) && (endToken.Parent.IsParentKind(SyntaxKind.TryStatement) || endToken.Parent.IsParentKind(SyntaxKind.DoStatement)); } public async Task<IList<TextChange>> FormatTokenAsync( Workspace workspace, SyntaxToken token, CancellationToken cancellationToken) { Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None || token.Kind() == SyntaxKind.EndOfFileToken); // get previous token var previousToken = token.GetPreviousToken(includeZeroWidth: true); if (previousToken.Kind() == SyntaxKind.None) { // no previous token. nothing to format return SpecializedCollections.EmptyList<TextChange>(); } // This is a heuristic to prevent brace completion from breaking user expectation/muscle memory in common scenarios (see Devdiv:823958). // Formatter uses FindToken on the position, which returns token to left, if there is nothing to the right and returns token to the right // if there exists one. If the shape is "{|}", we're including '}' in the formatting range. Avoid doing that to improve verbatim typing // in the following special scenarios. var adjustedEndPosition = token.Span.End; if (token.IsKind(SyntaxKind.OpenBraceToken) && (token.Parent.IsInitializerForArrayOrCollectionCreationExpression() || token.Parent is AnonymousObjectCreationExpressionSyntax)) { var nextToken = token.GetNextToken(includeZeroWidth: true); if (nextToken.IsKind(SyntaxKind.CloseBraceToken)) { // Format upto '{' and exclude '}' adjustedEndPosition = token.SpanStart; } } var smartTokenformattingRules = (new SmartTokenFormattingRule()).Concat(_formattingRules); var adjustedStartPosition = previousToken.SpanStart; var indentStyle = _optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp); if (token.IsKind(SyntaxKind.OpenBraceToken) && indentStyle != FormattingOptions.IndentStyle.Smart) { RoslynDebug.AssertNotNull(token.SyntaxTree); var text = await token.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); if (token.IsFirstTokenOnLine(text)) { adjustedStartPosition = token.SpanStart; } } return Formatter.GetFormattedTextChanges(_root, new TextSpan[] { TextSpan.FromBounds(adjustedStartPosition, adjustedEndPosition) }, workspace, _optionSet, smartTokenformattingRules, cancellationToken); } private class NoLineChangeFormattingRule : AbstractFormattingRule { public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { // no line operation. no line changes what so ever var lineOperation = base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); if (lineOperation != null) { // ignore force if same line option if (lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine) { return null; } // basically means don't ever put new line if there isn't already one, but do // indentation. return FormattingOperations.CreateAdjustNewLinesOperation(line: 0, option: AdjustNewLinesOption.PreserveLines); } return null; } } private class SmartTokenFormattingRule : NoLineChangeFormattingRule { public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) { // don't suppress anything } public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { var spaceOperation = base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); // if there is force space operation, convert it to ForceSpaceIfSingleLine operation. // (force space basically means remove all line breaks) if (spaceOperation != null && spaceOperation.Option == AdjustSpacesOption.ForceSpaces) { return FormattingOperations.CreateAdjustSpacesOperation(spaceOperation.Space, AdjustSpacesOption.ForceSpacesIfOnSingleLine); } return spaceOperation; } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/ExtractInterface/ExtractInterfaceTestState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface { internal class ExtractInterfaceTestState : IDisposable { public static readonly TestComposition Composition = EditorTestCompositions.EditorFeatures.AddParts( typeof(TestExtractInterfaceOptionsService)); private readonly TestHostDocument _testDocument; public TestWorkspace Workspace { get; } public Document ExtractFromDocument { get; } public AbstractExtractInterfaceService ExtractInterfaceService { get; } public Solution OriginalSolution { get; } public string ErrorMessage { get; private set; } public NotificationSeverity ErrorSeverity { get; private set; } public static ExtractInterfaceTestState Create(string markup, string languageName, CompilationOptions compilationOptions) { var workspace = languageName == LanguageNames.CSharp ? TestWorkspace.CreateCSharp(markup, composition: Composition, compilationOptions: (CSharpCompilationOptions)compilationOptions) : TestWorkspace.CreateVisualBasic(markup, composition: Composition, compilationOptions: compilationOptions); return new ExtractInterfaceTestState(workspace); } public ExtractInterfaceTestState(TestWorkspace workspace) { Workspace = workspace; OriginalSolution = Workspace.CurrentSolution; _testDocument = Workspace.Documents.SingleOrDefault(d => d.CursorPosition.HasValue); if (_testDocument == null) { throw new ArgumentException("markup does not contain a cursor position", nameof(workspace)); } ExtractFromDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id); ExtractInterfaceService = ExtractFromDocument.GetLanguageService<AbstractExtractInterfaceService>(); } public TestExtractInterfaceOptionsService TestExtractInterfaceOptionsService { get { return (TestExtractInterfaceOptionsService)ExtractFromDocument.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); } } public Task<ExtractInterfaceTypeAnalysisResult> GetTypeAnalysisResultAsync(TypeDiscoveryRule typeDiscoveryRule) { return ExtractInterfaceService.AnalyzeTypeAtPositionAsync( ExtractFromDocument, _testDocument.CursorPosition.Value, typeDiscoveryRule, CancellationToken.None); } public Task<ExtractInterfaceResult> ExtractViaCommandAsync() { return ExtractInterfaceService.ExtractInterfaceAsync( ExtractFromDocument, _testDocument.CursorPosition.Value, (errorMessage, severity) => { this.ErrorMessage = errorMessage; this.ErrorSeverity = severity; }, CancellationToken.None); } public async Task<Solution> ExtractViaCodeAction() { var actions = await ExtractInterfaceService.GetExtractInterfaceCodeActionAsync( ExtractFromDocument, new TextSpan(_testDocument.CursorPosition.Value, 1), CancellationToken.None); var action = actions.Single(); var options = (ExtractInterfaceOptionsResult)action.GetOptions(CancellationToken.None); var changedOptions = new ExtractInterfaceOptionsResult( options.IsCancelled, options.IncludedMembers, options.InterfaceName, options.FileName, ExtractInterfaceOptionsResult.ExtractLocation.SameFile); var operations = await action.GetOperationsAsync(changedOptions, CancellationToken.None); foreach (var operation in operations) { operation.Apply(Workspace, CancellationToken.None); } return Workspace.CurrentSolution; } public void Dispose() { if (Workspace != null) { Workspace.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface { internal class ExtractInterfaceTestState : IDisposable { public static readonly TestComposition Composition = EditorTestCompositions.EditorFeatures.AddParts( typeof(TestExtractInterfaceOptionsService)); private readonly TestHostDocument _testDocument; public TestWorkspace Workspace { get; } public Document ExtractFromDocument { get; } public AbstractExtractInterfaceService ExtractInterfaceService { get; } public Solution OriginalSolution { get; } public string ErrorMessage { get; private set; } public NotificationSeverity ErrorSeverity { get; private set; } public static ExtractInterfaceTestState Create(string markup, string languageName, CompilationOptions compilationOptions) { var workspace = languageName == LanguageNames.CSharp ? TestWorkspace.CreateCSharp(markup, composition: Composition, compilationOptions: (CSharpCompilationOptions)compilationOptions) : TestWorkspace.CreateVisualBasic(markup, composition: Composition, compilationOptions: compilationOptions); return new ExtractInterfaceTestState(workspace); } public ExtractInterfaceTestState(TestWorkspace workspace) { Workspace = workspace; OriginalSolution = Workspace.CurrentSolution; _testDocument = Workspace.Documents.SingleOrDefault(d => d.CursorPosition.HasValue); if (_testDocument == null) { throw new ArgumentException("markup does not contain a cursor position", nameof(workspace)); } ExtractFromDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id); ExtractInterfaceService = ExtractFromDocument.GetLanguageService<AbstractExtractInterfaceService>(); } public TestExtractInterfaceOptionsService TestExtractInterfaceOptionsService { get { return (TestExtractInterfaceOptionsService)ExtractFromDocument.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); } } public Task<ExtractInterfaceTypeAnalysisResult> GetTypeAnalysisResultAsync(TypeDiscoveryRule typeDiscoveryRule) { return ExtractInterfaceService.AnalyzeTypeAtPositionAsync( ExtractFromDocument, _testDocument.CursorPosition.Value, typeDiscoveryRule, CancellationToken.None); } public Task<ExtractInterfaceResult> ExtractViaCommandAsync() { return ExtractInterfaceService.ExtractInterfaceAsync( ExtractFromDocument, _testDocument.CursorPosition.Value, (errorMessage, severity) => { this.ErrorMessage = errorMessage; this.ErrorSeverity = severity; }, CancellationToken.None); } public async Task<Solution> ExtractViaCodeAction() { var actions = await ExtractInterfaceService.GetExtractInterfaceCodeActionAsync( ExtractFromDocument, new TextSpan(_testDocument.CursorPosition.Value, 1), CancellationToken.None); var action = actions.Single(); var options = (ExtractInterfaceOptionsResult)action.GetOptions(CancellationToken.None); var changedOptions = new ExtractInterfaceOptionsResult( options.IsCancelled, options.IncludedMembers, options.InterfaceName, options.FileName, ExtractInterfaceOptionsResult.ExtractLocation.SameFile); var operations = await action.GetOperationsAsync(changedOptions, CancellationToken.None); foreach (var operation in operations) { operation.Apply(Workspace, CancellationToken.None); } return Workspace.CurrentSolution; } public void Dispose() { if (Workspace != null) { Workspace.Dispose(); } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/CodeFixes/FileHeaders/CSharpFileHeaderCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.FileHeaders; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.FileHeaders { /// <summary> /// Implements a code fix for file header diagnostics. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.FileHeader)] [Shared] internal class CSharpFileHeaderCodeFixProvider : AbstractFileHeaderCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFileHeaderCodeFixProvider() { } protected override AbstractFileHeaderHelper FileHeaderHelper => CSharpFileHeaderHelper.Instance; protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override ISyntaxKinds SyntaxKinds => CSharpSyntaxKinds.Instance; protected override SyntaxTrivia EndOfLine(string text) => SyntaxFactory.EndOfLine(text); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.FileHeaders; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.FileHeaders { /// <summary> /// Implements a code fix for file header diagnostics. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.FileHeader)] [Shared] internal class CSharpFileHeaderCodeFixProvider : AbstractFileHeaderCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFileHeaderCodeFixProvider() { } protected override AbstractFileHeaderHelper FileHeaderHelper => CSharpFileHeaderHelper.Instance; protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override ISyntaxKinds SyntaxKinds => CSharpSyntaxKinds.Instance; protected override SyntaxTrivia EndOfLine(string text) => SyntaxFactory.EndOfLine(text); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisValueProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Diagnostics { internal class AnalysisValueProvider<TKey, TValue> where TKey : class { private readonly Func<TKey, TValue> _computeValue; // This provider holds a weak reference to the key-value pairs, as AnalysisValueProvider might outlive individual compilations. // CompilationAnalysisValueProvider, which wraps this provider and lives for the lifetime of specific compilation, holds a strong reference to the key-value pairs, providing an overall performance benefit. private readonly ConditionalWeakTable<TKey, WrappedValue> _valueCache; private readonly ConditionalWeakTable<TKey, WrappedValue>.CreateValueCallback _valueCacheCallback; internal IEqualityComparer<TKey> KeyComparer { get; private set; } public AnalysisValueProvider(Func<TKey, TValue> computeValue, IEqualityComparer<TKey> keyComparer) { _computeValue = computeValue; KeyComparer = keyComparer ?? EqualityComparer<TKey>.Default; _valueCache = new ConditionalWeakTable<TKey, WrappedValue>(); _valueCacheCallback = new ConditionalWeakTable<TKey, WrappedValue>.CreateValueCallback(ComputeValue); } private sealed class WrappedValue { public WrappedValue(TValue value) { Value = value; } public TValue Value { get; } } private WrappedValue ComputeValue(TKey key) { var value = _computeValue(key); return new WrappedValue(value); } internal bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { // Catch any exceptions from the computeValue callback, which calls into user code. try { value = _valueCache.GetValue(key, _valueCacheCallback).Value; Debug.Assert(value is object); return true; } catch (Exception) { value = default; 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Diagnostics { internal class AnalysisValueProvider<TKey, TValue> where TKey : class { private readonly Func<TKey, TValue> _computeValue; // This provider holds a weak reference to the key-value pairs, as AnalysisValueProvider might outlive individual compilations. // CompilationAnalysisValueProvider, which wraps this provider and lives for the lifetime of specific compilation, holds a strong reference to the key-value pairs, providing an overall performance benefit. private readonly ConditionalWeakTable<TKey, WrappedValue> _valueCache; private readonly ConditionalWeakTable<TKey, WrappedValue>.CreateValueCallback _valueCacheCallback; internal IEqualityComparer<TKey> KeyComparer { get; private set; } public AnalysisValueProvider(Func<TKey, TValue> computeValue, IEqualityComparer<TKey> keyComparer) { _computeValue = computeValue; KeyComparer = keyComparer ?? EqualityComparer<TKey>.Default; _valueCache = new ConditionalWeakTable<TKey, WrappedValue>(); _valueCacheCallback = new ConditionalWeakTable<TKey, WrappedValue>.CreateValueCallback(ComputeValue); } private sealed class WrappedValue { public WrappedValue(TValue value) { Value = value; } public TValue Value { get; } } private WrappedValue ComputeValue(TKey key) { var value = _computeValue(key); return new WrappedValue(value); } internal bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { // Catch any exceptions from the computeValue callback, which calls into user code. try { value = _valueCache.GetValue(key, _valueCacheCallback).Value; Debug.Assert(value is object); return true; } catch (Exception) { value = default; return false; } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class SymbolMatcherTests : EditAndContinueTestBase { private static PEAssemblySymbol CreatePEAssemblySymbol(string source) { var compilation = CreateCompilation(source, options: TestOptions.DebugDll); var reference = compilation.EmitToImageReference(); return (PEAssemblySymbol)CreateCompilation("", new[] { reference }).GetReferencedAssemblySymbol(reference); } [Fact] public void ConcurrentAccess() { var source = @"class A { B F; D P { get; set; } void M(A a, B b, S s, I i) { } delegate void D(S s); class B { } struct S { } interface I { } } class B { A M<T, U>() where T : A where U : T, I { return null; } event D E; delegate void D(S s); struct S { } interface I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var builder = new List<Symbol>(); var type = compilation1.GetMember<NamedTypeSymbol>("A"); builder.Add(type); builder.AddRange(type.GetMembers()); type = compilation1.GetMember<NamedTypeSymbol>("B"); builder.Add(type); builder.AddRange(type.GetMembers()); var members = builder.ToImmutableArray(); Assert.True(members.Length > 10); for (int i = 0; i < 10; i++) { var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var tasks = new Task[10]; for (int j = 0; j < tasks.Length; j++) { int startAt = i + j + 1; tasks[j] = Task.Run(() => { MatchAll(matcher, members, startAt); Thread.Sleep(10); }); } Task.WaitAll(tasks); } } private static void MatchAll(CSharpSymbolMatcher matcher, ImmutableArray<Symbol> members, int startAt) { int n = members.Length; for (int i = 0; i < n; i++) { var member = members[(i + startAt) % n]; var other = matcher.MapDefinition((Cci.IDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void TypeArguments() { const string source = @"class A<T> { class B<U> { static A<V> M<V>(A<U>.B<T> x, A<object>.S y) { return null; } static A<V> M<V>(A<U>.B<T> x, A<V>.S y) { return null; } } struct S { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMember<NamedTypeSymbol>("A.B").GetMembers("M"); Assert.Equal(2, members.Length); foreach (var member in members) { var other = matcher.MapDefinition((Cci.IMethodDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void Constraints() { const string source = @"interface I<T> where T : I<T> { } class C { static void M<T>(I<T> o) where T : I<T> { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void CustomModifiers() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) *p) { } }"; var metadataRef = CompileIL(ilSource); var source = @"unsafe class B : A { public override object[] F(int* p) { return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { metadataRef }); var compilation1 = compilation0.WithSource(source); var member1 = compilation1.GetMember<MethodSymbol>("B.F"); Assert.Equal(1, ((PointerTypeSymbol)member1.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)member1.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var other = (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(); Assert.NotNull(other); Assert.Equal(1, ((PointerTypeSymbol)other.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)other.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); } [Fact] public void CustomModifiers_InAttribute_Source() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Same(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [Fact] public void CustomModifiers_InAttribute_Metadata() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var peAssemblySymbol = CreatePEAssemblySymbol(source0); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll).WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, peAssemblySymbol); var f0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("F"); var g0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Equal(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Equal(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [ConditionalFact(typeof(DesktopOnly))] public void VaryingCompilationReferences() { string libSource = @" public class D { } "; string source = @" public class C { public void F(D a) {} } "; var lib0 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var lib1 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var compilation0 = CreateCompilation(source, new[] { lib0.ToMetadataReference() }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var mf1 = matcher.MapDefinition(f1.GetCciAdapter()); Assert.Equal(f0, mf1.GetInternalSymbol()); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void PreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } class D {} }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); Assert.NotNull(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_PointerType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static unsafe void M() { D* x = null; } struct D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreatePointerTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_GenericType() { var source0 = @" using System.Collections.Generic; class C { static void M() { int x = 0; } }"; var source1 = @" using System.Collections.Generic; class C { static void M() { List<D> x = null; } class D {} List<D> y; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.y"); var other = matcher.MapReference((Cci.ITypeReference)member.Type.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [Fact] public void HoistedAnonymousTypes() { var source0 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { B = 1 }; var y = new Func<int>(() => x1.A + x2.B); } } "; var source1 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { b = 1 }; var y = new Func<int>(() => x1.A + x2.b); } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var x1 = fields[0]; var x2 = fields[1]; Assert.Equal("x1", x1.Name); Assert.Equal("x2", x2.Name); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void HoistedAnonymousTypes_Complex() { var source0 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Y = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Y); } } "; var source1 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Z = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Z); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("X", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType2", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("Y", isKey: false, ignoreCase: false)))].Name); Assert.Equal(3, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x1", "x2" }); var x1 = fields.Where(f => f.Name == "x1").Single(); var x2 = fields.Where(f => f.Name == "x2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void TupleField_TypeChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, bool b) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleField_NameChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, int c) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleMethod_TypeChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, bool b) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleMethod_NameChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, int c) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleProperty_TypeChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, bool b) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleProperty_NameChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, int c) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleStructField_TypeChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int y, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleStructField_NameChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleDelegate_TypeChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int, bool) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Tuple delegate defines a type. We should be able to match old and new types by name. Assert.NotNull(other); } [Fact] public void TupleDelegate_NameChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int x, int y) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void RefReturn_Method() { var source0 = @" struct C { // non-matching public ref int P() => throw null; public ref readonly int Q() => throw null; public int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P() => throw null; public ref int Q() => throw null; public ref int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<MethodSymbol>("C.S"); var t0 = compilation0.GetMember<MethodSymbol>("C.T"); var p1 = compilation1.GetMember<MethodSymbol>("C.P"); var q1 = compilation1.GetMember<MethodSymbol>("C.Q"); var r1 = compilation1.GetMember<MethodSymbol>("C.R"); var s1 = compilation1.GetMember<MethodSymbol>("C.S"); var t1 = compilation1.GetMember<MethodSymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void RefReturn_Property() { var source0 = @" struct C { // non-matching public ref int P => throw null; public ref readonly int Q => throw null; public int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P => throw null; public ref int Q => throw null; public ref int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<PropertySymbol>("C.S"); var t0 = compilation0.GetMember<PropertySymbol>("C.T"); var p1 = compilation1.GetMember<PropertySymbol>("C.P"); var q1 = compilation1.GetMember<PropertySymbol>("C.Q"); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var s1 = compilation1.GetMember<PropertySymbol>("C.S"); var t1 = compilation1.GetMember<PropertySymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Property_CompilationVsPE() { var source = @" using System; interface I<T, S> { int this[int index] { set; } } class C : I<int, bool> { int _current; int I<int, bool>.this[int anotherIndex] { set { _current = anotherIndex + value; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var property = c.GetMember<PropertySymbol>("I<System.Int32,System.Boolean>.this[]"); var parameters = property.GetParameters().ToArray(); Assert.Equal(1, parameters.Length); Assert.Equal("anotherIndex", parameters[0].Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher(null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedProperty = (Cci.IPropertyDefinition)matcher.MapDefinition(property.GetCciAdapter()); Assert.Equal("I<System.Int32,System.Boolean>.Item", ((PropertySymbol)mappedProperty.GetInternalSymbol()).MetadataName); } [Fact] public void Method_ParameterNullableChange() { var source0 = @" using System.Collections.Generic; class C { string c; ref string M(string? s, (string a, dynamic? b) tuple, List<string?> list) => ref c; }"; var source1 = @" using System.Collections.Generic; class C { string c; ref string? M(string s, (string? a, dynamic b) tuple, List<string> list) => ref c; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Field_NullableChange() { var source0 = @" class C { string S; }"; var source1 = @" class C { string? S; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.S"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void AnonymousTypesWithNullables() { var source0 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var source1 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { if (x is null) throw new Exception(); var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass2_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x", "y1", "y2" }); var y1 = fields.Where(f => f.Name == "y1").Single(); var y2 = fields.Where(f => f.Name == "y2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedY1 = (Cci.IFieldDefinition)matcher.MapDefinition(y1); var mappedY2 = (Cci.IFieldDefinition)matcher.MapDefinition(y2); Assert.Equal("y1", mappedY1.Name); Assert.Equal("y2", mappedY2.Name); } [Fact] public void InterfaceMembers() { var source = @" using System; interface I { static int X = 1; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var x0 = compilation0.GetMember<FieldSymbol>("I.X"); var y0 = compilation0.GetMember<EventSymbol>("I.Y"); var m0 = compilation0.GetMember<MethodSymbol>("I.M"); var n0 = compilation0.GetMember<MethodSymbol>("I.N"); var p0 = compilation0.GetMember<PropertySymbol>("I.P"); var q0 = compilation0.GetMember<PropertySymbol>("I.Q"); var e0 = compilation0.GetMember<EventSymbol>("I.E"); var f0 = compilation0.GetMember<EventSymbol>("I.F"); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); Assert.Same(x0, matcher.MapDefinition(x1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(y0, matcher.MapDefinition(y1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(m0, matcher.MapDefinition(m1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(n0, matcher.MapDefinition(n1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(p0, matcher.MapDefinition(p1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(q0, matcher.MapDefinition(q1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(e0, matcher.MapDefinition(e1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(f0, matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void FunctionPointerMembersTranslated() { var source = @" unsafe class C { delegate*<void> f1; delegate*<C, C, C> f2; delegate*<ref C> f3; delegate*<ref readonly C> f4; delegate*<ref C, void> f5; delegate*<in C, void> f6; delegate*<out C, void> f7; } "; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); for (int i = 1; i <= 7; i++) { var f_0 = compilation0.GetMember<FieldSymbol>($"C.f{i}"); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f{i}"); Assert.Same(f_0, matcher.MapDefinition(f_1.GetCciAdapter()).GetInternalSymbol()); } } [Theory] [InlineData("C", "void")] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "ref readonly C")] [InlineData("ref C", "ref readonly C")] public void FunctionPointerMembers_ReturnMismatch(string return1, string return2) { var source1 = $@" unsafe class C {{ delegate*<C, {return1}> f1; }}"; var source2 = $@" unsafe class C {{ delegate*<C, {return2}> f1; }}"; var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } [Theory] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "out C")] [InlineData("C", "in C")] [InlineData("ref C", "out C")] [InlineData("ref C", "in C")] [InlineData("out C", "in C")] [InlineData("C, C", "C")] public void FunctionPointerMembers_ParamMismatch(string param1, string param2) { var source1 = $@" unsafe class C {{ delegate*<{param1}, C, void>* f1; }}"; var source2 = $@" unsafe class C {{ delegate*<{param2}, C, void>* f1; }}"; verify(source1, source2); source1 = $@" unsafe class C {{ delegate*<C, {param1}, void> f1; }}"; source2 = $@" unsafe class C {{ delegate*<C, {param2}, void> f1; }}"; verify(source1, source2); static void verify(string source1, string source2) { var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } } [Fact] public void Record_ImplementSynthesizedMember_ToString() { var source0 = @" public record R { }"; var source1 = @" public record R { public override string ToString() => ""R""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.ToString"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Record_ImplementSynthesizedMember_PrintMembers() { var source0 = @" public record R { }"; var source1 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); var member1 = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_RemoveSynthesizedMember_PrintMembers() { var source0 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var source1 = @" public record R { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); var member1 = compilation1.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Property() { var source0 = @" public record R(int X);"; var source1 = @" public record R(int X) { public int X { get; init; } = this.X; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPropertySymbol>("R.X"); var member1 = compilation1.GetMember<SourcePropertySymbol>("R.X"); Assert.Equal(member0, (PropertySymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Constructor() { var source0 = @" public record R(int X);"; var source1 = @" public record R { public R(int X) { this.X = X; } public int X { get; init; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMembers("R..ctor"); // There are two, one is the copy constructor Assert.Equal(2, members.Length); var member = (SourceConstructorSymbol)members.Single(m => m.ToString() == "R.R(int)"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class SymbolMatcherTests : EditAndContinueTestBase { private static PEAssemblySymbol CreatePEAssemblySymbol(string source) { var compilation = CreateCompilation(source, options: TestOptions.DebugDll); var reference = compilation.EmitToImageReference(); return (PEAssemblySymbol)CreateCompilation("", new[] { reference }).GetReferencedAssemblySymbol(reference); } [Fact] public void ConcurrentAccess() { var source = @"class A { B F; D P { get; set; } void M(A a, B b, S s, I i) { } delegate void D(S s); class B { } struct S { } interface I { } } class B { A M<T, U>() where T : A where U : T, I { return null; } event D E; delegate void D(S s); struct S { } interface I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var builder = new List<Symbol>(); var type = compilation1.GetMember<NamedTypeSymbol>("A"); builder.Add(type); builder.AddRange(type.GetMembers()); type = compilation1.GetMember<NamedTypeSymbol>("B"); builder.Add(type); builder.AddRange(type.GetMembers()); var members = builder.ToImmutableArray(); Assert.True(members.Length > 10); for (int i = 0; i < 10; i++) { var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var tasks = new Task[10]; for (int j = 0; j < tasks.Length; j++) { int startAt = i + j + 1; tasks[j] = Task.Run(() => { MatchAll(matcher, members, startAt); Thread.Sleep(10); }); } Task.WaitAll(tasks); } } private static void MatchAll(CSharpSymbolMatcher matcher, ImmutableArray<Symbol> members, int startAt) { int n = members.Length; for (int i = 0; i < n; i++) { var member = members[(i + startAt) % n]; var other = matcher.MapDefinition((Cci.IDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void TypeArguments() { const string source = @"class A<T> { class B<U> { static A<V> M<V>(A<U>.B<T> x, A<object>.S y) { return null; } static A<V> M<V>(A<U>.B<T> x, A<V>.S y) { return null; } } struct S { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMember<NamedTypeSymbol>("A.B").GetMembers("M"); Assert.Equal(2, members.Length); foreach (var member in members) { var other = matcher.MapDefinition((Cci.IMethodDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void Constraints() { const string source = @"interface I<T> where T : I<T> { } class C { static void M<T>(I<T> o) where T : I<T> { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void CustomModifiers() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) *p) { } }"; var metadataRef = CompileIL(ilSource); var source = @"unsafe class B : A { public override object[] F(int* p) { return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { metadataRef }); var compilation1 = compilation0.WithSource(source); var member1 = compilation1.GetMember<MethodSymbol>("B.F"); Assert.Equal(1, ((PointerTypeSymbol)member1.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)member1.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var other = (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(); Assert.NotNull(other); Assert.Equal(1, ((PointerTypeSymbol)other.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)other.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); } [Fact] public void CustomModifiers_InAttribute_Source() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Same(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [Fact] public void CustomModifiers_InAttribute_Metadata() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var peAssemblySymbol = CreatePEAssemblySymbol(source0); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll).WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, peAssemblySymbol); var f0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("F"); var g0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Equal(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Equal(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [ConditionalFact(typeof(DesktopOnly))] public void VaryingCompilationReferences() { string libSource = @" public class D { } "; string source = @" public class C { public void F(D a) {} } "; var lib0 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var lib1 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var compilation0 = CreateCompilation(source, new[] { lib0.ToMetadataReference() }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var mf1 = matcher.MapDefinition(f1.GetCciAdapter()); Assert.Equal(f0, mf1.GetInternalSymbol()); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void PreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } class D {} }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); Assert.NotNull(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_PointerType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static unsafe void M() { D* x = null; } struct D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreatePointerTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_GenericType() { var source0 = @" using System.Collections.Generic; class C { static void M() { int x = 0; } }"; var source1 = @" using System.Collections.Generic; class C { static void M() { List<D> x = null; } class D {} List<D> y; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.y"); var other = matcher.MapReference((Cci.ITypeReference)member.Type.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [Fact] public void HoistedAnonymousTypes() { var source0 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { B = 1 }; var y = new Func<int>(() => x1.A + x2.B); } } "; var source1 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { b = 1 }; var y = new Func<int>(() => x1.A + x2.b); } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var x1 = fields[0]; var x2 = fields[1]; Assert.Equal("x1", x1.Name); Assert.Equal("x2", x2.Name); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void HoistedAnonymousTypes_Complex() { var source0 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Y = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Y); } } "; var source1 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Z = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Z); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("X", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType2", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("Y", isKey: false, ignoreCase: false)))].Name); Assert.Equal(3, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x1", "x2" }); var x1 = fields.Where(f => f.Name == "x1").Single(); var x2 = fields.Where(f => f.Name == "x2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void TupleField_TypeChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, bool b) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleField_NameChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, int c) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleMethod_TypeChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, bool b) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleMethod_NameChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, int c) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleProperty_TypeChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, bool b) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleProperty_NameChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, int c) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleStructField_TypeChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int y, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleStructField_NameChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleDelegate_TypeChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int, bool) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Tuple delegate defines a type. We should be able to match old and new types by name. Assert.NotNull(other); } [Fact] public void TupleDelegate_NameChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int x, int y) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void RefReturn_Method() { var source0 = @" struct C { // non-matching public ref int P() => throw null; public ref readonly int Q() => throw null; public int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P() => throw null; public ref int Q() => throw null; public ref int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<MethodSymbol>("C.S"); var t0 = compilation0.GetMember<MethodSymbol>("C.T"); var p1 = compilation1.GetMember<MethodSymbol>("C.P"); var q1 = compilation1.GetMember<MethodSymbol>("C.Q"); var r1 = compilation1.GetMember<MethodSymbol>("C.R"); var s1 = compilation1.GetMember<MethodSymbol>("C.S"); var t1 = compilation1.GetMember<MethodSymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void RefReturn_Property() { var source0 = @" struct C { // non-matching public ref int P => throw null; public ref readonly int Q => throw null; public int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P => throw null; public ref int Q => throw null; public ref int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<PropertySymbol>("C.S"); var t0 = compilation0.GetMember<PropertySymbol>("C.T"); var p1 = compilation1.GetMember<PropertySymbol>("C.P"); var q1 = compilation1.GetMember<PropertySymbol>("C.Q"); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var s1 = compilation1.GetMember<PropertySymbol>("C.S"); var t1 = compilation1.GetMember<PropertySymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Property_CompilationVsPE() { var source = @" using System; interface I<T, S> { int this[int index] { set; } } class C : I<int, bool> { int _current; int I<int, bool>.this[int anotherIndex] { set { _current = anotherIndex + value; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var property = c.GetMember<PropertySymbol>("I<System.Int32,System.Boolean>.this[]"); var parameters = property.GetParameters().ToArray(); Assert.Equal(1, parameters.Length); Assert.Equal("anotherIndex", parameters[0].Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher(null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedProperty = (Cci.IPropertyDefinition)matcher.MapDefinition(property.GetCciAdapter()); Assert.Equal("I<System.Int32,System.Boolean>.Item", ((PropertySymbol)mappedProperty.GetInternalSymbol()).MetadataName); } [Fact] public void Method_ParameterNullableChange() { var source0 = @" using System.Collections.Generic; class C { string c; ref string M(string? s, (string a, dynamic? b) tuple, List<string?> list) => ref c; }"; var source1 = @" using System.Collections.Generic; class C { string c; ref string? M(string s, (string? a, dynamic b) tuple, List<string> list) => ref c; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Field_NullableChange() { var source0 = @" class C { string S; }"; var source1 = @" class C { string? S; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.S"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void AnonymousTypesWithNullables() { var source0 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var source1 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { if (x is null) throw new Exception(); var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass2_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x", "y1", "y2" }); var y1 = fields.Where(f => f.Name == "y1").Single(); var y2 = fields.Where(f => f.Name == "y2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedY1 = (Cci.IFieldDefinition)matcher.MapDefinition(y1); var mappedY2 = (Cci.IFieldDefinition)matcher.MapDefinition(y2); Assert.Equal("y1", mappedY1.Name); Assert.Equal("y2", mappedY2.Name); } [Fact] public void InterfaceMembers() { var source = @" using System; interface I { static int X = 1; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var x0 = compilation0.GetMember<FieldSymbol>("I.X"); var y0 = compilation0.GetMember<EventSymbol>("I.Y"); var m0 = compilation0.GetMember<MethodSymbol>("I.M"); var n0 = compilation0.GetMember<MethodSymbol>("I.N"); var p0 = compilation0.GetMember<PropertySymbol>("I.P"); var q0 = compilation0.GetMember<PropertySymbol>("I.Q"); var e0 = compilation0.GetMember<EventSymbol>("I.E"); var f0 = compilation0.GetMember<EventSymbol>("I.F"); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); Assert.Same(x0, matcher.MapDefinition(x1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(y0, matcher.MapDefinition(y1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(m0, matcher.MapDefinition(m1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(n0, matcher.MapDefinition(n1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(p0, matcher.MapDefinition(p1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(q0, matcher.MapDefinition(q1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(e0, matcher.MapDefinition(e1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(f0, matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void FunctionPointerMembersTranslated() { var source = @" unsafe class C { delegate*<void> f1; delegate*<C, C, C> f2; delegate*<ref C> f3; delegate*<ref readonly C> f4; delegate*<ref C, void> f5; delegate*<in C, void> f6; delegate*<out C, void> f7; } "; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); for (int i = 1; i <= 7; i++) { var f_0 = compilation0.GetMember<FieldSymbol>($"C.f{i}"); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f{i}"); Assert.Same(f_0, matcher.MapDefinition(f_1.GetCciAdapter()).GetInternalSymbol()); } } [Theory] [InlineData("C", "void")] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "ref readonly C")] [InlineData("ref C", "ref readonly C")] public void FunctionPointerMembers_ReturnMismatch(string return1, string return2) { var source1 = $@" unsafe class C {{ delegate*<C, {return1}> f1; }}"; var source2 = $@" unsafe class C {{ delegate*<C, {return2}> f1; }}"; var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } [Theory] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "out C")] [InlineData("C", "in C")] [InlineData("ref C", "out C")] [InlineData("ref C", "in C")] [InlineData("out C", "in C")] [InlineData("C, C", "C")] public void FunctionPointerMembers_ParamMismatch(string param1, string param2) { var source1 = $@" unsafe class C {{ delegate*<{param1}, C, void>* f1; }}"; var source2 = $@" unsafe class C {{ delegate*<{param2}, C, void>* f1; }}"; verify(source1, source2); source1 = $@" unsafe class C {{ delegate*<C, {param1}, void> f1; }}"; source2 = $@" unsafe class C {{ delegate*<C, {param2}, void> f1; }}"; verify(source1, source2); static void verify(string source1, string source2) { var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } } [Fact] public void Record_ImplementSynthesizedMember_ToString() { var source0 = @" public record R { }"; var source1 = @" public record R { public override string ToString() => ""R""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.ToString"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Record_ImplementSynthesizedMember_PrintMembers() { var source0 = @" public record R { }"; var source1 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); var member1 = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_RemoveSynthesizedMember_PrintMembers() { var source0 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var source1 = @" public record R { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); var member1 = compilation1.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Property() { var source0 = @" public record R(int X);"; var source1 = @" public record R(int X) { public int X { get; init; } = this.X; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPropertySymbol>("R.X"); var member1 = compilation1.GetMember<SourcePropertySymbol>("R.X"); Assert.Equal(member0, (PropertySymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Constructor() { var source0 = @" public record R(int X);"; var source1 = @" public record R { public R(int X) { this.X = X; } public int X { get; init; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMembers("R..ctor"); // There are two, one is the copy constructor Assert.Equal(2, members.Length); var member = (SourceConstructorSymbol)members.Single(m => m.ToString() == "R.R(int)"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/StateMachineStates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal static class StateMachineStates { internal const int FinishedStateMachine = -2; internal const int NotStartedStateMachine = -1; internal const int FirstUnusedState = 0; // used for async-iterators to distinguish initial state from running state (-1) so that DisposeAsync can throw in latter case internal const int InitialAsyncIteratorStateMachine = -3; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal static class StateMachineStates { internal const int FinishedStateMachine = -2; internal const int NotStartedStateMachine = -1; internal const int FirstUnusedState = 0; // used for async-iterators to distinguish initial state from running state (-1) so that DisposeAsync can throw in latter case internal const int InitialAsyncIteratorStateMachine = -3; } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayLocalOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how locals are displayed in the description of a symbol. /// </summary> [Flags] public enum SymbolDisplayLocalOptions { /// <summary> /// Shows only the name of the local. /// For example, "x". /// </summary> None = 0, /// <summary> /// Shows the type of the local in addition to its name. /// For example, "int x" in C# or "x As Integer" in Visual Basic. /// </summary> IncludeType = 1 << 0, /// <summary> /// Shows the constant value of the local, if there is one, in addition to its name. /// For example "x = 1". /// </summary> IncludeConstantValue = 1 << 1, /// <summary> /// Includes the <c>ref</c> keyword for ref-locals. /// </summary> IncludeRef = 1 << 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how locals are displayed in the description of a symbol. /// </summary> [Flags] public enum SymbolDisplayLocalOptions { /// <summary> /// Shows only the name of the local. /// For example, "x". /// </summary> None = 0, /// <summary> /// Shows the type of the local in addition to its name. /// For example, "int x" in C# or "x As Integer" in Visual Basic. /// </summary> IncludeType = 1 << 0, /// <summary> /// Shows the constant value of the local, if there is one, in addition to its name. /// For example "x = 1". /// </summary> IncludeConstantValue = 1 << 1, /// <summary> /// Includes the <c>ref</c> keyword for ref-locals. /// </summary> IncludeRef = 1 << 2, } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Xaml/Impl/Features/QuickInfo/XamlQuickInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal sealed class XamlQuickInfo { public TextSpan Span { get; } public IEnumerable<TaggedText> Description { get; } public ISymbol Symbol { get; } private XamlQuickInfo( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol) { Span = span; Description = description; Symbol = symbol; } public static XamlQuickInfo Create( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol = null) { return new XamlQuickInfo(span, description, symbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal sealed class XamlQuickInfo { public TextSpan Span { get; } public IEnumerable<TaggedText> Description { get; } public ISymbol Symbol { get; } private XamlQuickInfo( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol) { Span = span; Description = description; Symbol = symbol; } public static XamlQuickInfo Create( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol = null) { return new XamlQuickInfo(span, description, symbol); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Organizing/Organizers/StructDeclarationOrganizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 StructDeclarationOrganizer : AbstractSyntaxNodeOrganizer<StructDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StructDeclarationOrganizer() { } protected override StructDeclarationSyntax Organize( StructDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.Keyword, syntax.Identifier, syntax.TypeParameterList, syntax.BaseList, syntax.ConstraintClauses, syntax.OpenBraceToken, MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken), syntax.CloseBraceToken, 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 StructDeclarationOrganizer : AbstractSyntaxNodeOrganizer<StructDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StructDeclarationOrganizer() { } protected override StructDeclarationSyntax Organize( StructDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.Keyword, syntax.Identifier, syntax.TypeParameterList, syntax.BaseList, syntax.ConstraintClauses, syntax.OpenBraceToken, MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken), syntax.CloseBraceToken, syntax.SemicolonToken); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Syntax/SyntaxListBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal class SyntaxListBuilder { private ArrayElement<GreenNode?>[] _nodes; public int Count { get; private set; } public SyntaxListBuilder(int size) { _nodes = new ArrayElement<GreenNode?>[size]; } public void Clear() { this.Count = 0; } public void Add(SyntaxNode item) { AddInternal(item.Green); } internal void AddInternal(GreenNode item) { if (item == null) { throw new ArgumentNullException(); } if (Count >= _nodes.Length) { this.Grow(Count == 0 ? 8 : _nodes.Length * 2); } _nodes[Count++].Value = item; } public void AddRange(SyntaxNode[] items) { this.AddRange(items, 0, items.Length); } public void AddRange(SyntaxNode[] items, int offset, int length) { if (Count + length > _nodes.Length) { this.Grow(Count + length); } for (int i = offset, j = Count; i < offset + length; ++i, ++j) { _nodes[j].Value = items[i].Green; } int start = Count; Count += length; Validate(start, Count); } [Conditional("DEBUG")] private void Validate(int start, int end) { for (int i = start; i < end; i++) { if (_nodes[i].Value == null) { throw new ArgumentException("Cannot add a null node."); } } } public void AddRange(SyntaxList<SyntaxNode> list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxList<SyntaxNode> list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list.ItemInternal(i)!.Green; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange<TNode>(SyntaxList<TNode> list) where TNode : SyntaxNode { this.AddRange(list, 0, list.Count); } public void AddRange<TNode>(SyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { this.AddRange(new SyntaxList<SyntaxNode>(list.Node), offset, count); } public void AddRange(SyntaxNodeOrTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxNodeOrTokenList list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list[i].UnderlyingNode; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange(SyntaxTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxTokenList list, int offset, int length) { Debug.Assert(list.Node is object); this.AddRange(new SyntaxList<SyntaxNode>(list.Node.CreateRed()), offset, length); } private void Grow(int size) { var tmp = new ArrayElement<GreenNode?>[size]; Array.Copy(_nodes, tmp, _nodes.Length); _nodes = tmp; } public bool Any(int kind) { for (int i = 0; i < Count; i++) { if (_nodes[i].Value!.RawKind == kind) { return true; } } return false; } internal GreenNode? ToListNode() { switch (this.Count) { case 0: return null; case 1: return _nodes[0].Value; case 2: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!); case 3: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!, _nodes[2].Value!); default: var tmp = new ArrayElement<GreenNode>[this.Count]; for (int i = 0; i < this.Count; i++) { tmp[i].Value = _nodes[i].Value!; } return InternalSyntax.SyntaxList.List(tmp); } } public static implicit operator SyntaxList<SyntaxNode>(SyntaxListBuilder builder) { if (builder == null) { return default(SyntaxList<SyntaxNode>); } return builder.ToList(); } internal void RemoveLast() { this.Count -= 1; this._nodes[Count] = 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.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal class SyntaxListBuilder { private ArrayElement<GreenNode?>[] _nodes; public int Count { get; private set; } public SyntaxListBuilder(int size) { _nodes = new ArrayElement<GreenNode?>[size]; } public void Clear() { this.Count = 0; } public void Add(SyntaxNode item) { AddInternal(item.Green); } internal void AddInternal(GreenNode item) { if (item == null) { throw new ArgumentNullException(); } if (Count >= _nodes.Length) { this.Grow(Count == 0 ? 8 : _nodes.Length * 2); } _nodes[Count++].Value = item; } public void AddRange(SyntaxNode[] items) { this.AddRange(items, 0, items.Length); } public void AddRange(SyntaxNode[] items, int offset, int length) { if (Count + length > _nodes.Length) { this.Grow(Count + length); } for (int i = offset, j = Count; i < offset + length; ++i, ++j) { _nodes[j].Value = items[i].Green; } int start = Count; Count += length; Validate(start, Count); } [Conditional("DEBUG")] private void Validate(int start, int end) { for (int i = start; i < end; i++) { if (_nodes[i].Value == null) { throw new ArgumentException("Cannot add a null node."); } } } public void AddRange(SyntaxList<SyntaxNode> list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxList<SyntaxNode> list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list.ItemInternal(i)!.Green; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange<TNode>(SyntaxList<TNode> list) where TNode : SyntaxNode { this.AddRange(list, 0, list.Count); } public void AddRange<TNode>(SyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { this.AddRange(new SyntaxList<SyntaxNode>(list.Node), offset, count); } public void AddRange(SyntaxNodeOrTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxNodeOrTokenList list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list[i].UnderlyingNode; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange(SyntaxTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxTokenList list, int offset, int length) { Debug.Assert(list.Node is object); this.AddRange(new SyntaxList<SyntaxNode>(list.Node.CreateRed()), offset, length); } private void Grow(int size) { var tmp = new ArrayElement<GreenNode?>[size]; Array.Copy(_nodes, tmp, _nodes.Length); _nodes = tmp; } public bool Any(int kind) { for (int i = 0; i < Count; i++) { if (_nodes[i].Value!.RawKind == kind) { return true; } } return false; } internal GreenNode? ToListNode() { switch (this.Count) { case 0: return null; case 1: return _nodes[0].Value; case 2: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!); case 3: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!, _nodes[2].Value!); default: var tmp = new ArrayElement<GreenNode>[this.Count]; for (int i = 0; i < this.Count; i++) { tmp[i].Value = _nodes[i].Value!; } return InternalSyntax.SyntaxList.List(tmp); } } public static implicit operator SyntaxList<SyntaxNode>(SyntaxListBuilder builder) { if (builder == null) { return default(SyntaxList<SyntaxNode>); } return builder.ToList(); } internal void RemoveLast() { this.Count -= 1; this._nodes[Count] = default; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItemTracker.cs
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { /// <summary> /// This class listens to selection change events, and tracks which, if any, of our /// <see cref="AnalyzerItem"/> or <see cref="AnalyzersFolderItem"/> is selected. /// </summary> [Export] internal class AnalyzerItemsTracker : IVsSelectionEvents { private readonly IServiceProvider _serviceProvider; private IVsMonitorSelection? _vsMonitorSelection = null; private uint _selectionEventsCookie = 0; public event EventHandler? SelectedHierarchyItemChanged; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AnalyzerItemsTracker( [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public void Register() { var vsMonitorSelection = GetMonitorSelection(); if (vsMonitorSelection != null) { vsMonitorSelection.AdviseSelectionEvents(this, out _selectionEventsCookie); } } public void Unregister() { var vsMonitorSelection = GetMonitorSelection(); if (vsMonitorSelection != null) { vsMonitorSelection.UnadviseSelectionEvents(_selectionEventsCookie); } } public IVsHierarchy? SelectedHierarchy { get; private set; } public uint SelectedItemId { get; private set; } = VSConstants.VSITEMID_NIL; public AnalyzersFolderItem? SelectedFolder { get; private set; } public ImmutableArray<AnalyzerItem> SelectedAnalyzerItems { get; private set; } = ImmutableArray<AnalyzerItem>.Empty; public ImmutableArray<DiagnosticItem> SelectedDiagnosticItems { get; private set; } = ImmutableArray<DiagnosticItem>.Empty; int IVsSelectionEvents.OnCmdUIContextChanged(uint dwCmdUICookie, int fActive) { return VSConstants.S_OK; } int IVsSelectionEvents.OnElementValueChanged(uint elementid, object varValueOld, object varValueNew) { return VSConstants.S_OK; } int IVsSelectionEvents.OnSelectionChanged( IVsHierarchy pHierOld, uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew) { var oldSelectedHierarchy = this.SelectedHierarchy; var oldSelectedItemId = this.SelectedItemId; this.SelectedHierarchy = pHierNew; this.SelectedItemId = itemidNew; var selectedObjects = GetSelectedObjects(pSCNew); this.SelectedAnalyzerItems = selectedObjects .OfType<AnalyzerItem.BrowseObject>() .Select(b => b.AnalyzerItem) .ToImmutableArray(); this.SelectedFolder = selectedObjects .OfType<AnalyzersFolderItem.BrowseObject>() .Select(b => b.Folder) .FirstOrDefault(); this.SelectedDiagnosticItems = selectedObjects .OfType<DiagnosticItem.BrowseObject>() .Select(b => b.DiagnosticItem) .ToImmutableArray(); if (!object.ReferenceEquals(oldSelectedHierarchy, this.SelectedHierarchy) || oldSelectedItemId != this.SelectedItemId) { this.SelectedHierarchyItemChanged?.Invoke(this, EventArgs.Empty); } return VSConstants.S_OK; } private object[] GetSelectedObjects(ISelectionContainer? selectionContainer) { if (selectionContainer == null) { return Array.Empty<object>(); } if (selectionContainer.CountObjects((uint)Constants.GETOBJS_SELECTED, out var selectedObjectCount) < 0 || selectedObjectCount == 0) { return Array.Empty<object>(); } var selectedObjects = new object[selectedObjectCount]; if (selectionContainer.GetObjects((uint)Constants.GETOBJS_SELECTED, selectedObjectCount, selectedObjects) < 0) { return Array.Empty<object>(); } return selectedObjects; } private IVsMonitorSelection? GetMonitorSelection() { if (_vsMonitorSelection == null) { _vsMonitorSelection = _serviceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; } return _vsMonitorSelection; } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { /// <summary> /// This class listens to selection change events, and tracks which, if any, of our /// <see cref="AnalyzerItem"/> or <see cref="AnalyzersFolderItem"/> is selected. /// </summary> [Export] internal class AnalyzerItemsTracker : IVsSelectionEvents { private readonly IServiceProvider _serviceProvider; private IVsMonitorSelection? _vsMonitorSelection = null; private uint _selectionEventsCookie = 0; public event EventHandler? SelectedHierarchyItemChanged; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AnalyzerItemsTracker( [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public void Register() { var vsMonitorSelection = GetMonitorSelection(); if (vsMonitorSelection != null) { vsMonitorSelection.AdviseSelectionEvents(this, out _selectionEventsCookie); } } public void Unregister() { var vsMonitorSelection = GetMonitorSelection(); if (vsMonitorSelection != null) { vsMonitorSelection.UnadviseSelectionEvents(_selectionEventsCookie); } } public IVsHierarchy? SelectedHierarchy { get; private set; } public uint SelectedItemId { get; private set; } = VSConstants.VSITEMID_NIL; public AnalyzersFolderItem? SelectedFolder { get; private set; } public ImmutableArray<AnalyzerItem> SelectedAnalyzerItems { get; private set; } = ImmutableArray<AnalyzerItem>.Empty; public ImmutableArray<DiagnosticItem> SelectedDiagnosticItems { get; private set; } = ImmutableArray<DiagnosticItem>.Empty; int IVsSelectionEvents.OnCmdUIContextChanged(uint dwCmdUICookie, int fActive) { return VSConstants.S_OK; } int IVsSelectionEvents.OnElementValueChanged(uint elementid, object varValueOld, object varValueNew) { return VSConstants.S_OK; } int IVsSelectionEvents.OnSelectionChanged( IVsHierarchy pHierOld, uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew) { var oldSelectedHierarchy = this.SelectedHierarchy; var oldSelectedItemId = this.SelectedItemId; this.SelectedHierarchy = pHierNew; this.SelectedItemId = itemidNew; var selectedObjects = GetSelectedObjects(pSCNew); this.SelectedAnalyzerItems = selectedObjects .OfType<AnalyzerItem.BrowseObject>() .Select(b => b.AnalyzerItem) .ToImmutableArray(); this.SelectedFolder = selectedObjects .OfType<AnalyzersFolderItem.BrowseObject>() .Select(b => b.Folder) .FirstOrDefault(); this.SelectedDiagnosticItems = selectedObjects .OfType<DiagnosticItem.BrowseObject>() .Select(b => b.DiagnosticItem) .ToImmutableArray(); if (!object.ReferenceEquals(oldSelectedHierarchy, this.SelectedHierarchy) || oldSelectedItemId != this.SelectedItemId) { this.SelectedHierarchyItemChanged?.Invoke(this, EventArgs.Empty); } return VSConstants.S_OK; } private object[] GetSelectedObjects(ISelectionContainer? selectionContainer) { if (selectionContainer == null) { return Array.Empty<object>(); } if (selectionContainer.CountObjects((uint)Constants.GETOBJS_SELECTED, out var selectedObjectCount) < 0 || selectedObjectCount == 0) { return Array.Empty<object>(); } var selectedObjects = new object[selectedObjectCount]; if (selectionContainer.GetObjects((uint)Constants.GETOBJS_SELECTED, selectedObjectCount, selectedObjects) < 0) { return Array.Empty<object>(); } return selectedObjects; } private IVsMonitorSelection? GetMonitorSelection() { if (_vsMonitorSelection == null) { _vsMonitorSelection = _serviceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; } return _vsMonitorSelection; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/ExpressionSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ExpressionSyntaxExtensions { public static ExpressionSyntax WalkUpParentheses(this ExpressionSyntax expression) { while (expression.IsParentKind(SyntaxKind.ParenthesizedExpression, out ExpressionSyntax? parentExpr)) expression = parentExpr; return expression; } public static ExpressionSyntax WalkDownParentheses(this ExpressionSyntax expression) { while (expression.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpression)) expression = parenExpression.Expression; return expression; } public static bool IsQualifiedCrefName(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.NameMemberCref) && expression.Parent.IsParentKind(SyntaxKind.QualifiedCref); public static bool IsSimpleMemberAccessExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == expression; public static bool IsAnyMemberAccessExpressionName(this ExpressionSyntax expression) { if (expression == null) { return false; } return expression == (expression.Parent as MemberAccessExpressionSyntax)?.Name || expression.IsMemberBindingExpressionName(); } public static bool IsMemberBindingExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == expression; public static bool IsRightSideOfQualifiedName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Right == expression; public static bool IsRightSideOfColonColon(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.AliasQualifiedName, out AliasQualifiedNameSyntax? aliasName) && aliasName.Name == expression; public static bool IsRightSideOfDot(this ExpressionSyntax name) => IsSimpleMemberAccessExpressionName(name) || IsMemberBindingExpressionName(name) || IsRightSideOfQualifiedName(name) || IsQualifiedCrefName(name); public static bool IsRightSideOfDotOrArrow(this ExpressionSyntax name) => IsAnyMemberAccessExpressionName(name) || IsRightSideOfQualifiedName(name); public static bool IsRightSideOfDotOrColonColon(this ExpressionSyntax name) => IsRightSideOfDot(name) || IsRightSideOfColonColon(name); public static bool IsRightSideOfDotOrArrowOrColonColon([NotNullWhen(true)] this ExpressionSyntax name) => IsRightSideOfDotOrArrow(name) || IsRightSideOfColonColon(name); public static bool IsRightOfCloseParen(this ExpressionSyntax expression) { var firstToken = expression.GetFirstToken(); return firstToken.Kind() != SyntaxKind.None && firstToken.GetPreviousToken().Kind() == SyntaxKind.CloseParenToken; } public static bool IsLeftSideOfDot([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; return IsLeftSideOfQualifiedName(expression) || IsLeftSideOfSimpleMemberAccessExpression(expression); } public static bool IsLeftSideOfSimpleMemberAccessExpression(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Expression == expression; public static bool IsLeftSideOfDotOrArrow(this ExpressionSyntax expression) => IsLeftSideOfQualifiedName(expression) || (expression.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Expression == expression); public static bool IsLeftSideOfQualifiedName(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Left == expression; public static bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] this NameSyntax? name) => name.IsParentKind(SyntaxKind.ExplicitInterfaceSpecifier); public static bool IsExpressionOfInvocation(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation) && invocation.Expression == expression; public static bool TryGetNameParts(this ExpressionSyntax expression, [NotNullWhen(true)] out IList<string>? parts) { var partsList = new List<string>(); if (!TryGetNameParts(expression, partsList)) { parts = null; return false; } parts = partsList; return true; } public static bool TryGetNameParts(this ExpressionSyntax expression, List<string> parts) { if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess)) { if (!TryGetNameParts(memberAccess.Expression, parts)) { return false; } return AddSimpleName(memberAccess.Name, parts); } else if (expression.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName)) { if (!TryGetNameParts(qualifiedName.Left, parts)) { return false; } return AddSimpleName(qualifiedName.Right, parts); } else if (expression is SimpleNameSyntax simpleName) { return AddSimpleName(simpleName, parts); } else { return false; } } private static bool AddSimpleName(SimpleNameSyntax simpleName, List<string> parts) { if (!simpleName.IsKind(SyntaxKind.IdentifierName)) { return false; } parts.Add(simpleName.Identifier.ValueText); return true; } public static bool IsAnyLiteralExpression(this ExpressionSyntax expression) => expression is LiteralExpressionSyntax; public static bool IsInConstantContext([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; if (expression.GetAncestor<ParameterSyntax>() != null) return true; var attributeArgument = expression.GetAncestor<AttributeArgumentSyntax>(); if (attributeArgument != null) { if (attributeArgument.NameEquals == null || expression != attributeArgument.NameEquals.Name) { return true; } } if (expression.IsParentKind(SyntaxKind.ConstantPattern)) return true; // note: the above list is not intended to be exhaustive. If more cases // are discovered that should be considered 'constant' contexts in the // language, then this should be updated accordingly. return false; } public static bool IsInOutContext(this ExpressionSyntax expression) { return expression?.Parent is ArgumentSyntax argument && argument.Expression == expression && argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword; } public static bool IsInRefContext(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.RefExpression) || (expression?.Parent as ArgumentSyntax)?.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword; public static bool IsInInContext(this ExpressionSyntax expression) => (expression?.Parent as ArgumentSyntax)?.RefKindKeyword.Kind() == SyntaxKind.InKeyword; private static ExpressionSyntax GetExpressionToAnalyzeForWrites(ExpressionSyntax expression) { if (expression.IsRightSideOfDotOrArrow()) { expression = (ExpressionSyntax)expression.GetRequiredParent(); } expression = expression.WalkUpParentheses(); return expression; } public static bool IsOnlyWrittenTo(this ExpressionSyntax expression) { expression = GetExpressionToAnalyzeForWrites(expression); if (expression != null) { if (expression.IsInOutContext()) { return true; } if (expression.Parent != null) { if (expression.IsLeftSideOfAssignExpression()) { return true; } if (expression.IsAttributeNamedArgumentIdentifier()) { return true; } } if (IsExpressionOfArgumentInDeconstruction(expression)) { return true; } } return false; } /// <summary> /// If this declaration or identifier is part of a deconstruction, find the deconstruction. /// If found, returns either an assignment expression or a foreach variable statement. /// Returns null otherwise. /// /// copied from SyntaxExtensions.GetContainingDeconstruction /// </summary> private static bool IsExpressionOfArgumentInDeconstruction(ExpressionSyntax expr) { if (!expr.IsParentKind(SyntaxKind.Argument)) { return false; } while (true) { var parent = expr.Parent; if (parent == null) { return false; } switch (parent.Kind()) { case SyntaxKind.Argument: if (parent.Parent?.Kind() == SyntaxKind.TupleExpression) { expr = (TupleExpressionSyntax)parent.Parent; continue; } return false; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)parent).Left == expr) { return true; } return false; case SyntaxKind.ForEachVariableStatement: if (((ForEachVariableStatementSyntax)parent).Variable == expr) { return true; } return false; default: return false; } } } public static bool IsWrittenTo(this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression == null) return false; expression = GetExpressionToAnalyzeForWrites(expression); if (expression.IsOnlyWrittenTo()) return true; if (expression.IsInRefContext()) { // most cases of `ref x` will count as a potential write of `x`. An important exception is: // `ref readonly y = ref x`. In that case, because 'y' can't be written to, this would not // be a write of 'x'. if (expression is { Parent: { RawKind: (int)SyntaxKind.RefExpression, Parent: EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax { Type: RefTypeSyntax refType } } } } } && refType.ReadOnlyKeyword != default) { return false; } return true; } // Similar to `ref x`, `&x` allows reads and write of the value, meaning `x` may be (but is not definitely) // written to. if (expression.Parent.IsKind(SyntaxKind.AddressOfExpression)) return true; // We're written if we're used in a ++, or -- expression. if (expression.IsOperandOfIncrementOrDecrementExpression()) return true; if (expression.IsLeftSideOfAnyAssignExpression()) return true; // An extension method invocation with a ref-this parameter can write to an expression. if (expression.Parent is MemberAccessExpressionSyntax memberAccess && expression == memberAccess.Expression) { var symbol = semanticModel.GetSymbolInfo(memberAccess, cancellationToken).Symbol; if (symbol is IMethodSymbol { MethodKind: MethodKind.ReducedExtension, ReducedFrom: IMethodSymbol reducedFrom } && reducedFrom.Parameters.Length > 0 && reducedFrom.Parameters.First().RefKind == RefKind.Ref) { return true; } } return false; } public static bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] this ExpressionSyntax? expression) { var nameEquals = expression?.Parent as NameEqualsSyntax; return nameEquals.IsParentKind(SyntaxKind.AttributeArgument); } public static bool IsOperandOfIncrementOrDecrementExpression(this ExpressionSyntax expression) { if (expression?.Parent is SyntaxNode parent) { switch (parent.Kind()) { case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PreDecrementExpression: return true; } } return false; } public static bool IsNamedArgumentIdentifier(this ExpressionSyntax expression) => expression is IdentifierNameSyntax && expression.Parent is NameColonSyntax; public static bool IsInsideNameOfExpression( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { var invocation = expression?.GetAncestor<InvocationExpressionSyntax>(); if (invocation?.Expression is IdentifierNameSyntax name && name.Identifier.Text == SyntaxFacts.GetText(SyntaxKind.NameOfKeyword)) { return semanticModel.GetMemberGroup(name, cancellationToken).IsDefaultOrEmpty; } return false; } private static bool CanReplace(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Method: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: case SymbolKind.FunctionPointerType: return true; } return false; } public static bool CanReplaceWithRValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // An RValue can't be written into. // i.e. you can't replace "a" in "a = b" with "Goo() = b". return expression != null && !expression.IsWrittenTo(semanticModel, cancellationToken) && CanReplaceWithLValue(expression, semanticModel, cancellationToken); } public static bool CanReplaceWithLValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression.IsKind(SyntaxKind.StackAllocArrayCreationExpression)) { // Stack alloc is very interesting. While it appears to be an expression, it is only // such so it can appear in a variable decl. It is not a normal expression that can // go anywhere. return false; } if (expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.CollectionInitializerExpression) || expression.IsKind(SyntaxKind.ObjectInitializerExpression) || expression.IsKind(SyntaxKind.ComplexElementInitializerExpression)) { return false; } // literal can be always replaced. if (expression is LiteralExpressionSyntax && !expression.IsParentKind(SyntaxKind.UnaryMinusExpression)) { return true; } if (expression is TupleExpressionSyntax) { return true; } if (!(expression is ObjectCreationExpressionSyntax) && !(expression is AnonymousObjectCreationExpressionSyntax) && !expression.IsLeftSideOfAssignExpression()) { var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); if (!symbolInfo.GetBestOrAllSymbols().All(CanReplace)) { // If the expression is actually a reference to a type, then it can't be replaced // with an arbitrary expression. return false; } } // If we are a conditional access expression: // case (1) : obj?.Method(), obj1.obj2?.Property // case (2) : obj?.GetAnotherObj()?.Length, obj?.AnotherObj?.Length // in case (1), the entire expression forms the conditional access expression, which can be replaced with an LValue. // in case (2), the nested conditional access expression is ".GetAnotherObj()?.Length" or ".AnotherObj()?.Length" // essentially, the first expression (before the operator) in a nested conditional access expression // is some form of member binding expression and they cannot be replaced with an LValue. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return expression is { Parent: { RawKind: not (int)SyntaxKind.ConditionalAccessExpression } }; } if (expression.Parent == null) return false; switch (expression.Parent.Kind()) { case SyntaxKind.InvocationExpression: // Technically, you could introduce an LValue for "Goo" in "Goo()" even if "Goo" binds // to a method. (i.e. by assigning to a Func<...> type). However, this is so contrived // and none of the features that use this extension consider this replaceable. if (expression.IsKind(SyntaxKind.IdentifierName) || expression is MemberAccessExpressionSyntax) { // If it looks like a method then we don't allow it to be replaced if it is a // method (or if it doesn't bind). var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); return symbolInfo.GetBestOrAllSymbols().Any() && !symbolInfo.GetBestOrAllSymbols().Any(s => s is IMethodSymbol); } else { // It doesn't look like a method, we allow this to be replaced. return true; } // If the parent is a conditional access expression, we could introduce an LValue // for the given expression, unless it is itself a MemberBindingExpression or starts with one. // Case (1) : The WhenNotNull clause always starts with a MemberBindingExpression. // expression '.Method()' in a?.Method() // Case (2) : The Expression clause always starts with a MemberBindingExpression if // the grandparent is a conditional access expression. // expression '.Method' in a?.Method()?.Length // Case (3) : The child Conditional access expression always starts with a MemberBindingExpression if // the parent is a conditional access expression. This case is already covered before the parent kind switch case SyntaxKind.ConditionalAccessExpression: var parentConditionalAccessExpression = (ConditionalAccessExpressionSyntax)expression.Parent; return expression != parentConditionalAccessExpression.WhenNotNull && !parentConditionalAccessExpression.Parent.IsKind(SyntaxKind.ConditionalAccessExpression); case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: // Can't introduce a variable for the type portion of an is/as check. var isOrAsExpression = (BinaryExpressionSyntax)expression.Parent; return expression == isOrAsExpression.Left; case SyntaxKind.EqualsValueClause: case SyntaxKind.ExpressionStatement: case SyntaxKind.ArrayInitializerExpression: case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.Argument: case SyntaxKind.AttributeArgument: case SyntaxKind.AnonymousObjectMemberDeclarator: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.AwaitExpression: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.ArrayRankSpecifier: case SyntaxKind.ConditionalExpression: case SyntaxKind.IfStatement: case SyntaxKind.CatchFilterClause: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.InterpolatedStringExpression: case SyntaxKind.ComplexElementInitializerExpression: case SyntaxKind.Interpolation: case SyntaxKind.RefExpression: case SyntaxKind.LockStatement: case SyntaxKind.ElementAccessExpression: case SyntaxKind.SwitchExpressionArm: // Direct parent kind checks. return true; } if (expression.Parent is PrefixUnaryExpressionSyntax) { if (!(expression is LiteralExpressionSyntax && expression.IsParentKind(SyntaxKind.UnaryMinusExpression))) { return true; } } var parentNonExpression = expression.GetAncestors().SkipWhile(n => n is ExpressionSyntax).FirstOrDefault(); var topExpression = expression; while (topExpression.Parent is TypeSyntax typeSyntax) { topExpression = typeSyntax; } if (parentNonExpression != null && parentNonExpression.IsKind(SyntaxKind.FromClause, out FromClauseSyntax? fromClause) && topExpression != null && fromClause.Type == topExpression) { return false; } // Parent type checks. if (expression.Parent is PostfixUnaryExpressionSyntax || expression.Parent is BinaryExpressionSyntax || expression.Parent is AssignmentExpressionSyntax || expression.Parent is QueryClauseSyntax || expression.Parent is SelectOrGroupClauseSyntax || expression.Parent is CheckedExpressionSyntax) { return true; } // Specific child checks. if (expression.CheckParent<CommonForEachStatementSyntax>(f => f.Expression == expression) || expression.CheckParent<MemberAccessExpressionSyntax>(m => m.Expression == expression) || expression.CheckParent<CastExpressionSyntax>(c => c.Expression == expression)) { return true; } // Misc checks. if ((expression.IsParentKind(SyntaxKind.NameEquals) && expression.Parent.IsParentKind(SyntaxKind.AttributeArgument)) || expression.IsLeftSideOfAnyAssignExpression()) { return true; } return false; } public static bool CanAccessInstanceAndStaticMembersOffOf( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // Check for the Color Color case. // // color color: if you bind "A" and you get a symbol and the type of that symbol is // Q; and if you bind "A" *again* as a type and you get type Q, then both A.static // and A.instance are permitted if (expression is IdentifierNameSyntax) { var instanceSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (!(instanceSymbol is INamespaceOrTypeSymbol)) { var instanceType = instanceSymbol.GetSymbolType(); if (instanceType != null) { var speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); if (speculativeSymbolInfo.CandidateReason != CandidateReason.NotATypeOrNamespace) { var staticType = speculativeSymbolInfo.GetAnySymbol().GetSymbolType(); return SymbolEquivalenceComparer.Instance.Equals(instanceType, staticType); } } } } return false; } public static bool IsNameOfArgumentExpression(this ExpressionSyntax expression) { return expression is { Parent: { RawKind: (int)SyntaxKind.Argument, Parent: { RawKind: (int)SyntaxKind.ArgumentList, Parent: InvocationExpressionSyntax invocation } } } && invocation.IsNameOfInvocation(); } public static bool IsNameOfInvocation(this InvocationExpressionSyntax invocation) { return invocation.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword); } public static SimpleNameSyntax? GetRightmostName(this ExpressionSyntax node) { if (node is MemberAccessExpressionSyntax memberAccess && memberAccess.Name != null) { return memberAccess.Name; } if (node is QualifiedNameSyntax qualified && qualified.Right != null) { return qualified.Right; } if (node is SimpleNameSyntax simple) { return simple; } if (node is ConditionalAccessExpressionSyntax conditional) { return conditional.WhenNotNull.GetRightmostName(); } if (node is MemberBindingExpressionSyntax memberBinding) { return memberBinding.Name; } if (node is AliasQualifiedNameSyntax aliasQualifiedName && aliasQualifiedName.Name != null) { return aliasQualifiedName.Name; } return null; } public static OperatorPrecedence GetOperatorPrecedence(this ExpressionSyntax expression) { switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.ConditionalAccessExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.CheckedExpression: case SyntaxKind.UncheckedExpression: case SyntaxKind.AnonymousMethodExpression: // unsafe code case SyntaxKind.SizeOfExpression: case SyntaxKind.PointerMemberAccessExpression: // From C# spec, 7.3.1: // Primary: x.y x?.y x?[y] f(x) a[x] x++ x-- new typeof default checked unchecked delegate return OperatorPrecedence.Primary; case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.CastExpression: case SyntaxKind.AwaitExpression: // unsafe code. case SyntaxKind.PointerIndirectionExpression: case SyntaxKind.AddressOfExpression: // From C# spec, 7.3.1: // Unary: + - ! ~ ++x --x (T)x await Task return OperatorPrecedence.Unary; case SyntaxKind.RangeExpression: // From C# spec, https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#systemrange // Range: .. return OperatorPrecedence.Range; case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: // From C# spec, 7.3.1: // Multiplicative: * / % return OperatorPrecedence.Multiplicative; case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: // From C# spec, 7.3.1: // Additive: + - return OperatorPrecedence.Additive; case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: // From C# spec, 7.3.1: // Shift: << >> return OperatorPrecedence.Shift; case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: // From C# spec, 7.3.1: // Relational and type testing: < > <= >= is as return OperatorPrecedence.RelationalAndTypeTesting; case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: // From C# spec, 7.3.1: // Equality: == != return OperatorPrecedence.Equality; case SyntaxKind.BitwiseAndExpression: // From C# spec, 7.3.1: // Logical AND: & return OperatorPrecedence.LogicalAnd; case SyntaxKind.ExclusiveOrExpression: // From C# spec, 7.3.1: // Logical XOR: ^ return OperatorPrecedence.LogicalXor; case SyntaxKind.BitwiseOrExpression: // From C# spec, 7.3.1: // Logical OR: | return OperatorPrecedence.LogicalOr; case SyntaxKind.LogicalAndExpression: // From C# spec, 7.3.1: // Conditional AND: && return OperatorPrecedence.ConditionalAnd; case SyntaxKind.LogicalOrExpression: // From C# spec, 7.3.1: // Conditional AND: || return OperatorPrecedence.ConditionalOr; case SyntaxKind.CoalesceExpression: // From C# spec, 7.3.1: // Null coalescing: ?? return OperatorPrecedence.NullCoalescing; case SyntaxKind.ConditionalExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.Conditional; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.AssignmentAndLambdaExpression; case SyntaxKind.SwitchExpression: return OperatorPrecedence.Switch; default: return OperatorPrecedence.None; } } public static bool TryConvertToStatement( this ExpressionSyntax expression, SyntaxToken? semicolonTokenOpt, bool createReturnStatementForExpression, [NotNullWhen(true)] out StatementSyntax? statement) { // It's tricky to convert an arrow expression with directives over to a block. // We'd need to find and remove the directives *after* the arrow expression and // move them accordingly. So, for now, we just disallow this. if (expression.GetLeadingTrivia().Any(t => t.IsDirective)) { statement = null; return false; } var semicolonToken = semicolonTokenOpt ?? SyntaxFactory.Token(SyntaxKind.SemicolonToken); statement = ConvertToStatement(expression, semicolonToken, createReturnStatementForExpression); return true; } private static StatementSyntax ConvertToStatement(ExpressionSyntax expression, SyntaxToken semicolonToken, bool createReturnStatementForExpression) { if (expression.IsKind(SyntaxKind.ThrowExpression, out ThrowExpressionSyntax? throwExpression)) { return SyntaxFactory.ThrowStatement(throwExpression.ThrowKeyword, throwExpression.Expression, semicolonToken); } else if (createReturnStatementForExpression) { if (expression.GetLeadingTrivia().Any(t => t.IsSingleOrMultiLineComment())) { return SyntaxFactory.ReturnStatement(expression.WithLeadingTrivia(SyntaxFactory.ElasticSpace)) .WithSemicolonToken(semicolonToken) .WithLeadingTrivia(expression.GetLeadingTrivia()) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker); } else { return SyntaxFactory.ReturnStatement(expression) .WithSemicolonToken(semicolonToken); } } else { return SyntaxFactory.ExpressionStatement(expression) .WithSemicolonToken(semicolonToken); } } public static bool IsDirectChildOfMemberAccessExpression(this ExpressionSyntax expression) => expression?.Parent is MemberAccessExpressionSyntax; public static bool InsideCrefReference(this ExpressionSyntax expression) => expression.FirstAncestorOrSelf<XmlCrefAttributeSyntax>() != null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ExpressionSyntaxExtensions { public static ExpressionSyntax WalkUpParentheses(this ExpressionSyntax expression) { while (expression.IsParentKind(SyntaxKind.ParenthesizedExpression, out ExpressionSyntax? parentExpr)) expression = parentExpr; return expression; } public static ExpressionSyntax WalkDownParentheses(this ExpressionSyntax expression) { while (expression.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpression)) expression = parenExpression.Expression; return expression; } public static bool IsQualifiedCrefName(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.NameMemberCref) && expression.Parent.IsParentKind(SyntaxKind.QualifiedCref); public static bool IsSimpleMemberAccessExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == expression; public static bool IsAnyMemberAccessExpressionName(this ExpressionSyntax expression) { if (expression == null) { return false; } return expression == (expression.Parent as MemberAccessExpressionSyntax)?.Name || expression.IsMemberBindingExpressionName(); } public static bool IsMemberBindingExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == expression; public static bool IsRightSideOfQualifiedName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Right == expression; public static bool IsRightSideOfColonColon(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.AliasQualifiedName, out AliasQualifiedNameSyntax? aliasName) && aliasName.Name == expression; public static bool IsRightSideOfDot(this ExpressionSyntax name) => IsSimpleMemberAccessExpressionName(name) || IsMemberBindingExpressionName(name) || IsRightSideOfQualifiedName(name) || IsQualifiedCrefName(name); public static bool IsRightSideOfDotOrArrow(this ExpressionSyntax name) => IsAnyMemberAccessExpressionName(name) || IsRightSideOfQualifiedName(name); public static bool IsRightSideOfDotOrColonColon(this ExpressionSyntax name) => IsRightSideOfDot(name) || IsRightSideOfColonColon(name); public static bool IsRightSideOfDotOrArrowOrColonColon([NotNullWhen(true)] this ExpressionSyntax name) => IsRightSideOfDotOrArrow(name) || IsRightSideOfColonColon(name); public static bool IsRightOfCloseParen(this ExpressionSyntax expression) { var firstToken = expression.GetFirstToken(); return firstToken.Kind() != SyntaxKind.None && firstToken.GetPreviousToken().Kind() == SyntaxKind.CloseParenToken; } public static bool IsLeftSideOfDot([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; return IsLeftSideOfQualifiedName(expression) || IsLeftSideOfSimpleMemberAccessExpression(expression); } public static bool IsLeftSideOfSimpleMemberAccessExpression(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Expression == expression; public static bool IsLeftSideOfDotOrArrow(this ExpressionSyntax expression) => IsLeftSideOfQualifiedName(expression) || (expression.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Expression == expression); public static bool IsLeftSideOfQualifiedName(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Left == expression; public static bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] this NameSyntax? name) => name.IsParentKind(SyntaxKind.ExplicitInterfaceSpecifier); public static bool IsExpressionOfInvocation(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation) && invocation.Expression == expression; public static bool TryGetNameParts(this ExpressionSyntax expression, [NotNullWhen(true)] out IList<string>? parts) { var partsList = new List<string>(); if (!TryGetNameParts(expression, partsList)) { parts = null; return false; } parts = partsList; return true; } public static bool TryGetNameParts(this ExpressionSyntax expression, List<string> parts) { if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess)) { if (!TryGetNameParts(memberAccess.Expression, parts)) { return false; } return AddSimpleName(memberAccess.Name, parts); } else if (expression.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName)) { if (!TryGetNameParts(qualifiedName.Left, parts)) { return false; } return AddSimpleName(qualifiedName.Right, parts); } else if (expression is SimpleNameSyntax simpleName) { return AddSimpleName(simpleName, parts); } else { return false; } } private static bool AddSimpleName(SimpleNameSyntax simpleName, List<string> parts) { if (!simpleName.IsKind(SyntaxKind.IdentifierName)) { return false; } parts.Add(simpleName.Identifier.ValueText); return true; } public static bool IsAnyLiteralExpression(this ExpressionSyntax expression) => expression is LiteralExpressionSyntax; public static bool IsInConstantContext([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; if (expression.GetAncestor<ParameterSyntax>() != null) return true; var attributeArgument = expression.GetAncestor<AttributeArgumentSyntax>(); if (attributeArgument != null) { if (attributeArgument.NameEquals == null || expression != attributeArgument.NameEquals.Name) { return true; } } if (expression.IsParentKind(SyntaxKind.ConstantPattern)) return true; // note: the above list is not intended to be exhaustive. If more cases // are discovered that should be considered 'constant' contexts in the // language, then this should be updated accordingly. return false; } public static bool IsInOutContext(this ExpressionSyntax expression) { return expression?.Parent is ArgumentSyntax argument && argument.Expression == expression && argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword; } public static bool IsInRefContext(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.RefExpression) || (expression?.Parent as ArgumentSyntax)?.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword; public static bool IsInInContext(this ExpressionSyntax expression) => (expression?.Parent as ArgumentSyntax)?.RefKindKeyword.Kind() == SyntaxKind.InKeyword; private static ExpressionSyntax GetExpressionToAnalyzeForWrites(ExpressionSyntax expression) { if (expression.IsRightSideOfDotOrArrow()) { expression = (ExpressionSyntax)expression.GetRequiredParent(); } expression = expression.WalkUpParentheses(); return expression; } public static bool IsOnlyWrittenTo(this ExpressionSyntax expression) { expression = GetExpressionToAnalyzeForWrites(expression); if (expression != null) { if (expression.IsInOutContext()) { return true; } if (expression.Parent != null) { if (expression.IsLeftSideOfAssignExpression()) { return true; } if (expression.IsAttributeNamedArgumentIdentifier()) { return true; } } if (IsExpressionOfArgumentInDeconstruction(expression)) { return true; } } return false; } /// <summary> /// If this declaration or identifier is part of a deconstruction, find the deconstruction. /// If found, returns either an assignment expression or a foreach variable statement. /// Returns null otherwise. /// /// copied from SyntaxExtensions.GetContainingDeconstruction /// </summary> private static bool IsExpressionOfArgumentInDeconstruction(ExpressionSyntax expr) { if (!expr.IsParentKind(SyntaxKind.Argument)) { return false; } while (true) { var parent = expr.Parent; if (parent == null) { return false; } switch (parent.Kind()) { case SyntaxKind.Argument: if (parent.Parent?.Kind() == SyntaxKind.TupleExpression) { expr = (TupleExpressionSyntax)parent.Parent; continue; } return false; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)parent).Left == expr) { return true; } return false; case SyntaxKind.ForEachVariableStatement: if (((ForEachVariableStatementSyntax)parent).Variable == expr) { return true; } return false; default: return false; } } } public static bool IsWrittenTo(this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression == null) return false; expression = GetExpressionToAnalyzeForWrites(expression); if (expression.IsOnlyWrittenTo()) return true; if (expression.IsInRefContext()) { // most cases of `ref x` will count as a potential write of `x`. An important exception is: // `ref readonly y = ref x`. In that case, because 'y' can't be written to, this would not // be a write of 'x'. if (expression is { Parent: { RawKind: (int)SyntaxKind.RefExpression, Parent: EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax { Type: RefTypeSyntax refType } } } } } && refType.ReadOnlyKeyword != default) { return false; } return true; } // Similar to `ref x`, `&x` allows reads and write of the value, meaning `x` may be (but is not definitely) // written to. if (expression.Parent.IsKind(SyntaxKind.AddressOfExpression)) return true; // We're written if we're used in a ++, or -- expression. if (expression.IsOperandOfIncrementOrDecrementExpression()) return true; if (expression.IsLeftSideOfAnyAssignExpression()) return true; // An extension method invocation with a ref-this parameter can write to an expression. if (expression.Parent is MemberAccessExpressionSyntax memberAccess && expression == memberAccess.Expression) { var symbol = semanticModel.GetSymbolInfo(memberAccess, cancellationToken).Symbol; if (symbol is IMethodSymbol { MethodKind: MethodKind.ReducedExtension, ReducedFrom: IMethodSymbol reducedFrom } && reducedFrom.Parameters.Length > 0 && reducedFrom.Parameters.First().RefKind == RefKind.Ref) { return true; } } return false; } public static bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] this ExpressionSyntax? expression) { var nameEquals = expression?.Parent as NameEqualsSyntax; return nameEquals.IsParentKind(SyntaxKind.AttributeArgument); } public static bool IsOperandOfIncrementOrDecrementExpression(this ExpressionSyntax expression) { if (expression?.Parent is SyntaxNode parent) { switch (parent.Kind()) { case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PreDecrementExpression: return true; } } return false; } public static bool IsNamedArgumentIdentifier(this ExpressionSyntax expression) => expression is IdentifierNameSyntax && expression.Parent is NameColonSyntax; public static bool IsInsideNameOfExpression( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { var invocation = expression?.GetAncestor<InvocationExpressionSyntax>(); if (invocation?.Expression is IdentifierNameSyntax name && name.Identifier.Text == SyntaxFacts.GetText(SyntaxKind.NameOfKeyword)) { return semanticModel.GetMemberGroup(name, cancellationToken).IsDefaultOrEmpty; } return false; } private static bool CanReplace(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Method: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: case SymbolKind.FunctionPointerType: return true; } return false; } public static bool CanReplaceWithRValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // An RValue can't be written into. // i.e. you can't replace "a" in "a = b" with "Goo() = b". return expression != null && !expression.IsWrittenTo(semanticModel, cancellationToken) && CanReplaceWithLValue(expression, semanticModel, cancellationToken); } public static bool CanReplaceWithLValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression.IsKind(SyntaxKind.StackAllocArrayCreationExpression)) { // Stack alloc is very interesting. While it appears to be an expression, it is only // such so it can appear in a variable decl. It is not a normal expression that can // go anywhere. return false; } if (expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.CollectionInitializerExpression) || expression.IsKind(SyntaxKind.ObjectInitializerExpression) || expression.IsKind(SyntaxKind.ComplexElementInitializerExpression)) { return false; } // literal can be always replaced. if (expression is LiteralExpressionSyntax && !expression.IsParentKind(SyntaxKind.UnaryMinusExpression)) { return true; } if (expression is TupleExpressionSyntax) { return true; } if (!(expression is ObjectCreationExpressionSyntax) && !(expression is AnonymousObjectCreationExpressionSyntax) && !expression.IsLeftSideOfAssignExpression()) { var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); if (!symbolInfo.GetBestOrAllSymbols().All(CanReplace)) { // If the expression is actually a reference to a type, then it can't be replaced // with an arbitrary expression. return false; } } // If we are a conditional access expression: // case (1) : obj?.Method(), obj1.obj2?.Property // case (2) : obj?.GetAnotherObj()?.Length, obj?.AnotherObj?.Length // in case (1), the entire expression forms the conditional access expression, which can be replaced with an LValue. // in case (2), the nested conditional access expression is ".GetAnotherObj()?.Length" or ".AnotherObj()?.Length" // essentially, the first expression (before the operator) in a nested conditional access expression // is some form of member binding expression and they cannot be replaced with an LValue. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return expression is { Parent: { RawKind: not (int)SyntaxKind.ConditionalAccessExpression } }; } if (expression.Parent == null) return false; switch (expression.Parent.Kind()) { case SyntaxKind.InvocationExpression: // Technically, you could introduce an LValue for "Goo" in "Goo()" even if "Goo" binds // to a method. (i.e. by assigning to a Func<...> type). However, this is so contrived // and none of the features that use this extension consider this replaceable. if (expression.IsKind(SyntaxKind.IdentifierName) || expression is MemberAccessExpressionSyntax) { // If it looks like a method then we don't allow it to be replaced if it is a // method (or if it doesn't bind). var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); return symbolInfo.GetBestOrAllSymbols().Any() && !symbolInfo.GetBestOrAllSymbols().Any(s => s is IMethodSymbol); } else { // It doesn't look like a method, we allow this to be replaced. return true; } // If the parent is a conditional access expression, we could introduce an LValue // for the given expression, unless it is itself a MemberBindingExpression or starts with one. // Case (1) : The WhenNotNull clause always starts with a MemberBindingExpression. // expression '.Method()' in a?.Method() // Case (2) : The Expression clause always starts with a MemberBindingExpression if // the grandparent is a conditional access expression. // expression '.Method' in a?.Method()?.Length // Case (3) : The child Conditional access expression always starts with a MemberBindingExpression if // the parent is a conditional access expression. This case is already covered before the parent kind switch case SyntaxKind.ConditionalAccessExpression: var parentConditionalAccessExpression = (ConditionalAccessExpressionSyntax)expression.Parent; return expression != parentConditionalAccessExpression.WhenNotNull && !parentConditionalAccessExpression.Parent.IsKind(SyntaxKind.ConditionalAccessExpression); case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: // Can't introduce a variable for the type portion of an is/as check. var isOrAsExpression = (BinaryExpressionSyntax)expression.Parent; return expression == isOrAsExpression.Left; case SyntaxKind.EqualsValueClause: case SyntaxKind.ExpressionStatement: case SyntaxKind.ArrayInitializerExpression: case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.Argument: case SyntaxKind.AttributeArgument: case SyntaxKind.AnonymousObjectMemberDeclarator: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.AwaitExpression: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.ArrayRankSpecifier: case SyntaxKind.ConditionalExpression: case SyntaxKind.IfStatement: case SyntaxKind.CatchFilterClause: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.InterpolatedStringExpression: case SyntaxKind.ComplexElementInitializerExpression: case SyntaxKind.Interpolation: case SyntaxKind.RefExpression: case SyntaxKind.LockStatement: case SyntaxKind.ElementAccessExpression: case SyntaxKind.SwitchExpressionArm: // Direct parent kind checks. return true; } if (expression.Parent is PrefixUnaryExpressionSyntax) { if (!(expression is LiteralExpressionSyntax && expression.IsParentKind(SyntaxKind.UnaryMinusExpression))) { return true; } } var parentNonExpression = expression.GetAncestors().SkipWhile(n => n is ExpressionSyntax).FirstOrDefault(); var topExpression = expression; while (topExpression.Parent is TypeSyntax typeSyntax) { topExpression = typeSyntax; } if (parentNonExpression != null && parentNonExpression.IsKind(SyntaxKind.FromClause, out FromClauseSyntax? fromClause) && topExpression != null && fromClause.Type == topExpression) { return false; } // Parent type checks. if (expression.Parent is PostfixUnaryExpressionSyntax || expression.Parent is BinaryExpressionSyntax || expression.Parent is AssignmentExpressionSyntax || expression.Parent is QueryClauseSyntax || expression.Parent is SelectOrGroupClauseSyntax || expression.Parent is CheckedExpressionSyntax) { return true; } // Specific child checks. if (expression.CheckParent<CommonForEachStatementSyntax>(f => f.Expression == expression) || expression.CheckParent<MemberAccessExpressionSyntax>(m => m.Expression == expression) || expression.CheckParent<CastExpressionSyntax>(c => c.Expression == expression)) { return true; } // Misc checks. if ((expression.IsParentKind(SyntaxKind.NameEquals) && expression.Parent.IsParentKind(SyntaxKind.AttributeArgument)) || expression.IsLeftSideOfAnyAssignExpression()) { return true; } return false; } public static bool CanAccessInstanceAndStaticMembersOffOf( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // Check for the Color Color case. // // color color: if you bind "A" and you get a symbol and the type of that symbol is // Q; and if you bind "A" *again* as a type and you get type Q, then both A.static // and A.instance are permitted if (expression is IdentifierNameSyntax) { var instanceSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (!(instanceSymbol is INamespaceOrTypeSymbol)) { var instanceType = instanceSymbol.GetSymbolType(); if (instanceType != null) { var speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); if (speculativeSymbolInfo.CandidateReason != CandidateReason.NotATypeOrNamespace) { var staticType = speculativeSymbolInfo.GetAnySymbol().GetSymbolType(); return SymbolEquivalenceComparer.Instance.Equals(instanceType, staticType); } } } } return false; } public static bool IsNameOfArgumentExpression(this ExpressionSyntax expression) { return expression is { Parent: { RawKind: (int)SyntaxKind.Argument, Parent: { RawKind: (int)SyntaxKind.ArgumentList, Parent: InvocationExpressionSyntax invocation } } } && invocation.IsNameOfInvocation(); } public static bool IsNameOfInvocation(this InvocationExpressionSyntax invocation) { return invocation.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword); } public static SimpleNameSyntax? GetRightmostName(this ExpressionSyntax node) { if (node is MemberAccessExpressionSyntax memberAccess && memberAccess.Name != null) { return memberAccess.Name; } if (node is QualifiedNameSyntax qualified && qualified.Right != null) { return qualified.Right; } if (node is SimpleNameSyntax simple) { return simple; } if (node is ConditionalAccessExpressionSyntax conditional) { return conditional.WhenNotNull.GetRightmostName(); } if (node is MemberBindingExpressionSyntax memberBinding) { return memberBinding.Name; } if (node is AliasQualifiedNameSyntax aliasQualifiedName && aliasQualifiedName.Name != null) { return aliasQualifiedName.Name; } return null; } public static OperatorPrecedence GetOperatorPrecedence(this ExpressionSyntax expression) { switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.ConditionalAccessExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.CheckedExpression: case SyntaxKind.UncheckedExpression: case SyntaxKind.AnonymousMethodExpression: // unsafe code case SyntaxKind.SizeOfExpression: case SyntaxKind.PointerMemberAccessExpression: // From C# spec, 7.3.1: // Primary: x.y x?.y x?[y] f(x) a[x] x++ x-- new typeof default checked unchecked delegate return OperatorPrecedence.Primary; case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.CastExpression: case SyntaxKind.AwaitExpression: // unsafe code. case SyntaxKind.PointerIndirectionExpression: case SyntaxKind.AddressOfExpression: // From C# spec, 7.3.1: // Unary: + - ! ~ ++x --x (T)x await Task return OperatorPrecedence.Unary; case SyntaxKind.RangeExpression: // From C# spec, https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#systemrange // Range: .. return OperatorPrecedence.Range; case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: // From C# spec, 7.3.1: // Multiplicative: * / % return OperatorPrecedence.Multiplicative; case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: // From C# spec, 7.3.1: // Additive: + - return OperatorPrecedence.Additive; case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: // From C# spec, 7.3.1: // Shift: << >> return OperatorPrecedence.Shift; case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: // From C# spec, 7.3.1: // Relational and type testing: < > <= >= is as return OperatorPrecedence.RelationalAndTypeTesting; case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: // From C# spec, 7.3.1: // Equality: == != return OperatorPrecedence.Equality; case SyntaxKind.BitwiseAndExpression: // From C# spec, 7.3.1: // Logical AND: & return OperatorPrecedence.LogicalAnd; case SyntaxKind.ExclusiveOrExpression: // From C# spec, 7.3.1: // Logical XOR: ^ return OperatorPrecedence.LogicalXor; case SyntaxKind.BitwiseOrExpression: // From C# spec, 7.3.1: // Logical OR: | return OperatorPrecedence.LogicalOr; case SyntaxKind.LogicalAndExpression: // From C# spec, 7.3.1: // Conditional AND: && return OperatorPrecedence.ConditionalAnd; case SyntaxKind.LogicalOrExpression: // From C# spec, 7.3.1: // Conditional AND: || return OperatorPrecedence.ConditionalOr; case SyntaxKind.CoalesceExpression: // From C# spec, 7.3.1: // Null coalescing: ?? return OperatorPrecedence.NullCoalescing; case SyntaxKind.ConditionalExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.Conditional; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.AssignmentAndLambdaExpression; case SyntaxKind.SwitchExpression: return OperatorPrecedence.Switch; default: return OperatorPrecedence.None; } } public static bool TryConvertToStatement( this ExpressionSyntax expression, SyntaxToken? semicolonTokenOpt, bool createReturnStatementForExpression, [NotNullWhen(true)] out StatementSyntax? statement) { // It's tricky to convert an arrow expression with directives over to a block. // We'd need to find and remove the directives *after* the arrow expression and // move them accordingly. So, for now, we just disallow this. if (expression.GetLeadingTrivia().Any(t => t.IsDirective)) { statement = null; return false; } var semicolonToken = semicolonTokenOpt ?? SyntaxFactory.Token(SyntaxKind.SemicolonToken); statement = ConvertToStatement(expression, semicolonToken, createReturnStatementForExpression); return true; } private static StatementSyntax ConvertToStatement(ExpressionSyntax expression, SyntaxToken semicolonToken, bool createReturnStatementForExpression) { if (expression.IsKind(SyntaxKind.ThrowExpression, out ThrowExpressionSyntax? throwExpression)) { return SyntaxFactory.ThrowStatement(throwExpression.ThrowKeyword, throwExpression.Expression, semicolonToken); } else if (createReturnStatementForExpression) { if (expression.GetLeadingTrivia().Any(t => t.IsSingleOrMultiLineComment())) { return SyntaxFactory.ReturnStatement(expression.WithLeadingTrivia(SyntaxFactory.ElasticSpace)) .WithSemicolonToken(semicolonToken) .WithLeadingTrivia(expression.GetLeadingTrivia()) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker); } else { return SyntaxFactory.ReturnStatement(expression) .WithSemicolonToken(semicolonToken); } } else { return SyntaxFactory.ExpressionStatement(expression) .WithSemicolonToken(semicolonToken); } } public static bool IsDirectChildOfMemberAccessExpression(this ExpressionSyntax expression) => expression?.Parent is MemberAccessExpressionSyntax; public static bool InsideCrefReference(this ExpressionSyntax expression) => expression.FirstAncestorOrSelf<XmlCrefAttributeSyntax>() != null; } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/CodeAnalysisTest/LinePositionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class LinePositionTests { [Fact] public void Equality1() { EqualityUtil.RunAll( (left, right) => left == right, (left, right) => left != right, EqualityUnit.Create(new LinePosition(1, 2)).WithEqualValues(new LinePosition(1, 2)), EqualityUnit.Create(new LinePosition()).WithEqualValues(new LinePosition()), EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(1, 3)), EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(2, 2))); } [Fact] public void Ctor1() { Assert.Throws<ArgumentOutOfRangeException>( () => { var notUsed = new LinePosition(-1, 42); }); } [Fact] public void Ctor2() { Assert.Throws<ArgumentOutOfRangeException>( () => { var notUsed = new LinePosition(42, -1); }); } [Fact] public void Ctor3() { var lp = new LinePosition(42, 13); Assert.Equal(42, lp.Line); Assert.Equal(13, lp.Character); } // In general, different values are not required to have different hash codes. // But for perf reasons we want hash functions with a good distribution, // so we expect hash codes to differ if a single component is incremented. // But program correctness should be preserved even with a null hash function, // so we need a way to disable these tests during such correctness validation. #if !DISABLE_GOOD_HASH_TESTS [Fact] public void SaneHashCode() { var hash1 = new LinePosition(1, 1).GetHashCode(); var hash2 = new LinePosition(2, 2).GetHashCode(); var hash3 = new LinePosition(1, 2).GetHashCode(); var hash4 = new LinePosition(2, 1).GetHashCode(); Assert.NotEqual(hash1, hash2); Assert.NotEqual(hash1, hash3); Assert.NotEqual(hash1, hash4); Assert.NotEqual(hash2, hash3); Assert.NotEqual(hash2, hash4); Assert.NotEqual(hash3, hash4); } #endif [Fact] public void CompareTo() { Assert.Equal(0, new LinePosition(1, 1).CompareTo(new LinePosition(1, 1))); Assert.Equal(-1, Math.Sign(new LinePosition(1, 1).CompareTo(new LinePosition(1, 2)))); Assert.True(new LinePosition(1, 1) < new LinePosition(1, 2)); Assert.Equal(-1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(2, 1)))); Assert.True(new LinePosition(1, 2) < new LinePosition(2, 1)); Assert.True(new LinePosition(1, 2) <= new LinePosition(1, 2)); Assert.True(new LinePosition(1, 2) <= new LinePosition(2, 1)); Assert.Equal(+1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(1, 1)))); Assert.True(new LinePosition(1, 2) > new LinePosition(1, 1)); Assert.Equal(+1, Math.Sign(new LinePosition(2, 1).CompareTo(new LinePosition(1, 2)))); Assert.True(new LinePosition(2, 1) > new LinePosition(1, 2)); Assert.True(new LinePosition(2, 1) >= new LinePosition(2, 1)); Assert.True(new LinePosition(2, 1) >= new LinePosition(1, 2)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class LinePositionTests { [Fact] public void Equality1() { EqualityUtil.RunAll( (left, right) => left == right, (left, right) => left != right, EqualityUnit.Create(new LinePosition(1, 2)).WithEqualValues(new LinePosition(1, 2)), EqualityUnit.Create(new LinePosition()).WithEqualValues(new LinePosition()), EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(1, 3)), EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(2, 2))); } [Fact] public void Ctor1() { Assert.Throws<ArgumentOutOfRangeException>( () => { var notUsed = new LinePosition(-1, 42); }); } [Fact] public void Ctor2() { Assert.Throws<ArgumentOutOfRangeException>( () => { var notUsed = new LinePosition(42, -1); }); } [Fact] public void Ctor3() { var lp = new LinePosition(42, 13); Assert.Equal(42, lp.Line); Assert.Equal(13, lp.Character); } // In general, different values are not required to have different hash codes. // But for perf reasons we want hash functions with a good distribution, // so we expect hash codes to differ if a single component is incremented. // But program correctness should be preserved even with a null hash function, // so we need a way to disable these tests during such correctness validation. #if !DISABLE_GOOD_HASH_TESTS [Fact] public void SaneHashCode() { var hash1 = new LinePosition(1, 1).GetHashCode(); var hash2 = new LinePosition(2, 2).GetHashCode(); var hash3 = new LinePosition(1, 2).GetHashCode(); var hash4 = new LinePosition(2, 1).GetHashCode(); Assert.NotEqual(hash1, hash2); Assert.NotEqual(hash1, hash3); Assert.NotEqual(hash1, hash4); Assert.NotEqual(hash2, hash3); Assert.NotEqual(hash2, hash4); Assert.NotEqual(hash3, hash4); } #endif [Fact] public void CompareTo() { Assert.Equal(0, new LinePosition(1, 1).CompareTo(new LinePosition(1, 1))); Assert.Equal(-1, Math.Sign(new LinePosition(1, 1).CompareTo(new LinePosition(1, 2)))); Assert.True(new LinePosition(1, 1) < new LinePosition(1, 2)); Assert.Equal(-1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(2, 1)))); Assert.True(new LinePosition(1, 2) < new LinePosition(2, 1)); Assert.True(new LinePosition(1, 2) <= new LinePosition(1, 2)); Assert.True(new LinePosition(1, 2) <= new LinePosition(2, 1)); Assert.Equal(+1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(1, 1)))); Assert.True(new LinePosition(1, 2) > new LinePosition(1, 1)); Assert.Equal(+1, Math.Sign(new LinePosition(2, 1).CompareTo(new LinePosition(1, 2)))); Assert.True(new LinePosition(2, 1) > new LinePosition(1, 2)); Assert.True(new LinePosition(2, 1) >= new LinePosition(2, 1)); Assert.True(new LinePosition(2, 1) >= new LinePosition(1, 2)); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Test/CodeModel/AbstractFileCodeElementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using EnvDTE; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Roslyn.Test.Utilities; using SyntaxNodeKey = Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.SyntaxNodeKey; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { /// <summary> /// Base class of a all test-containing classes. Automatically creates a FileCodeModel for testing with the given /// file. /// </summary> [UseExportProvider] public abstract class AbstractFileCodeElementTests : IDisposable { private readonly string _contents; private (TestWorkspace workspace, VisualStudioWorkspace extraWorkspaceToDisposeButNotUse, FileCodeModel fileCodeModel)? _workspaceAndCodeModel; protected AbstractFileCodeElementTests(string contents) { _contents = contents; } public (TestWorkspace workspace, VisualStudioWorkspace extraWorkspaceToDisposeButNotUse, FileCodeModel fileCodeModel) WorkspaceAndCodeModel { get { return _workspaceAndCodeModel ??= CreateWorkspaceAndFileCodeModelAsync(_contents); } } protected TestWorkspace GetWorkspace() { return WorkspaceAndCodeModel.workspace; } private VisualStudioWorkspace GetExtraWorkspaceToDisposeButNotUse() { return WorkspaceAndCodeModel.extraWorkspaceToDisposeButNotUse; } protected FileCodeModel GetCodeModel() { return WorkspaceAndCodeModel.fileCodeModel; } protected Microsoft.CodeAnalysis.Solution GetCurrentSolution() => GetWorkspace().CurrentSolution; protected Microsoft.CodeAnalysis.Project GetCurrentProject() => GetCurrentSolution().Projects.Single(); protected Microsoft.CodeAnalysis.Document GetCurrentDocument() => GetCurrentProject().Documents.Single(); protected static (TestWorkspace workspace, VisualStudioWorkspace extraWorkspaceToDisposeButNotUse, FileCodeModel fileCodeModel) CreateWorkspaceAndFileCodeModelAsync(string file) => FileCodeModelTestHelpers.CreateWorkspaceAndFileCodeModel(file); protected CodeElement GetCodeElement(params object[] path) { WpfTestRunner.RequireWpfFact($"Tests create {nameof(CodeElement)}s which use the affinitized {nameof(CleanableWeakComHandleTable<SyntaxNodeKey, CodeElement>)}"); if (path.Length == 0) { throw new ArgumentException("path must be non-empty.", nameof(path)); } var codeElement = (GetCodeModel()).CodeElements.Item(path[0]); foreach (var pathElement in path.Skip(1)) { codeElement = codeElement.Children.Item(pathElement); } return codeElement; } public void Dispose() { GetExtraWorkspaceToDisposeButNotUse().Dispose(); GetWorkspace().Dispose(); } /// <summary> /// Returns the current text of the test buffer. /// </summary> protected string GetFileText() { return (GetWorkspace()).Documents.Single().GetTextBuffer().CurrentSnapshot.GetText(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using EnvDTE; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Roslyn.Test.Utilities; using SyntaxNodeKey = Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.SyntaxNodeKey; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { /// <summary> /// Base class of a all test-containing classes. Automatically creates a FileCodeModel for testing with the given /// file. /// </summary> [UseExportProvider] public abstract class AbstractFileCodeElementTests : IDisposable { private readonly string _contents; private (TestWorkspace workspace, VisualStudioWorkspace extraWorkspaceToDisposeButNotUse, FileCodeModel fileCodeModel)? _workspaceAndCodeModel; protected AbstractFileCodeElementTests(string contents) { _contents = contents; } public (TestWorkspace workspace, VisualStudioWorkspace extraWorkspaceToDisposeButNotUse, FileCodeModel fileCodeModel) WorkspaceAndCodeModel { get { return _workspaceAndCodeModel ??= CreateWorkspaceAndFileCodeModelAsync(_contents); } } protected TestWorkspace GetWorkspace() { return WorkspaceAndCodeModel.workspace; } private VisualStudioWorkspace GetExtraWorkspaceToDisposeButNotUse() { return WorkspaceAndCodeModel.extraWorkspaceToDisposeButNotUse; } protected FileCodeModel GetCodeModel() { return WorkspaceAndCodeModel.fileCodeModel; } protected Microsoft.CodeAnalysis.Solution GetCurrentSolution() => GetWorkspace().CurrentSolution; protected Microsoft.CodeAnalysis.Project GetCurrentProject() => GetCurrentSolution().Projects.Single(); protected Microsoft.CodeAnalysis.Document GetCurrentDocument() => GetCurrentProject().Documents.Single(); protected static (TestWorkspace workspace, VisualStudioWorkspace extraWorkspaceToDisposeButNotUse, FileCodeModel fileCodeModel) CreateWorkspaceAndFileCodeModelAsync(string file) => FileCodeModelTestHelpers.CreateWorkspaceAndFileCodeModel(file); protected CodeElement GetCodeElement(params object[] path) { WpfTestRunner.RequireWpfFact($"Tests create {nameof(CodeElement)}s which use the affinitized {nameof(CleanableWeakComHandleTable<SyntaxNodeKey, CodeElement>)}"); if (path.Length == 0) { throw new ArgumentException("path must be non-empty.", nameof(path)); } var codeElement = (GetCodeModel()).CodeElements.Item(path[0]); foreach (var pathElement in path.Skip(1)) { codeElement = codeElement.Children.Item(pathElement); } return codeElement; } public void Dispose() { GetExtraWorkspaceToDisposeButNotUse().Dispose(); GetWorkspace().Dispose(); } /// <summary> /// Returns the current text of the test buffer. /// </summary> protected string GetFileText() { return (GetWorkspace()).Documents.Single().GetTextBuffer().CurrentSnapshot.GetText(); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyAccessorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class SourcePropertyAccessorSymbol : SourceMemberMethodSymbol { private readonly SourcePropertySymbolBase _property; private ImmutableArray<ParameterSymbol> _lazyParameters; private TypeWithAnnotations _lazyReturnType; private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; private ImmutableArray<MethodSymbol> _lazyExplicitInterfaceImplementations; private string _lazyName; private readonly bool _isAutoPropertyAccessor; private readonly bool _isExpressionBodied; private readonly bool _usesInit; public static SourcePropertyAccessorSymbol CreateAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, AccessorDeclarationSyntax syntax, bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax.Kind() == SyntaxKind.GetAccessorDeclaration || syntax.Kind() == SyntaxKind.SetAccessorDeclaration || syntax.Kind() == SyntaxKind.InitAccessorDeclaration); bool isGetMethod = (syntax.Kind() == SyntaxKind.GetAccessorDeclaration); var methodKind = isGetMethod ? MethodKind.PropertyGet : MethodKind.PropertySet; bool hasBody = syntax.Body is object; bool hasExpressionBody = syntax.ExpressionBody is object; bool isNullableAnalysisEnabled = containingType.DeclaringCompilation.IsNullableAnalysisEnabledIn(syntax); CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); return new SourcePropertyAccessorSymbol( containingType, property, propertyModifiers, syntax.Keyword.GetLocation(), syntax, hasBody, hasExpressionBody, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), syntax.Modifiers, methodKind, syntax.Keyword.IsKind(SyntaxKind.InitKeyword), isAutoPropertyAccessor, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics); } public static SourcePropertyAccessorSymbol CreateAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, ArrowExpressionClauseSyntax syntax, BindingDiagnosticBag diagnostics) { bool isNullableAnalysisEnabled = containingType.DeclaringCompilation.IsNullableAnalysisEnabledIn(syntax); return new SourcePropertyAccessorSymbol( containingType, property, propertyModifiers, syntax.Expression.GetLocation(), syntax, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics); } #nullable enable public static SourcePropertyAccessorSymbol CreateAccessorSymbol( bool isGetMethod, bool usesInit, NamedTypeSymbol containingType, SynthesizedRecordPropertySymbol property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { var methodKind = isGetMethod ? MethodKind.PropertyGet : MethodKind.PropertySet; return new SourcePropertyAccessorSymbol( containingType, property, propertyModifiers, location, syntax, hasBody: false, hasExpressionBody: false, isIterator: false, modifiers: new SyntaxTokenList(), methodKind, usesInit, isAutoPropertyAccessor: true, isNullableAnalysisEnabled: false, diagnostics); } public static SourcePropertyAccessorSymbol CreateAccessorSymbol( NamedTypeSymbol containingType, SynthesizedRecordEqualityContractProperty property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { return new SynthesizedRecordEqualityContractProperty.GetAccessorSymbol( containingType, property, propertyModifiers, location, syntax, diagnostics); } #nullable disable internal sealed override bool IsExpressionBodied => _isExpressionBodied; internal sealed override ImmutableArray<string> NotNullMembers => _property.NotNullMembers.Concat(base.NotNullMembers); internal sealed override ImmutableArray<string> NotNullWhenTrueMembers => _property.NotNullWhenTrueMembers.Concat(base.NotNullWhenTrueMembers); internal sealed override ImmutableArray<string> NotNullWhenFalseMembers => _property.NotNullWhenFalseMembers.Concat(base.NotNullWhenFalseMembers); private SourcePropertyAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, Location location, ArrowExpressionClauseSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: false) { _property = property; _isAutoPropertyAccessor = false; _isExpressionBodied = true; // The modifiers for the accessor are the same as the modifiers for the property, // minus the indexer and readonly bit var declarationModifiers = GetAccessorModifiers(propertyModifiers); // ReturnsVoid property is overridden in this class so // returnsVoid argument to MakeFlags is ignored. this.MakeFlags(MethodKind.PropertyGet, declarationModifiers, returnsVoid: false, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: property.IsExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody: true, diagnostics: diagnostics); CheckModifiersForBody(location, diagnostics); var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, property.IsExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } this.CheckModifiers(location, hasBody: true, isAutoPropertyOrExpressionBodied: true, diagnostics: diagnostics); } #nullable enable protected SourcePropertyAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, bool hasBody, bool hasExpressionBody, bool isIterator, SyntaxTokenList modifiers, MethodKind methodKind, bool usesInit, bool isAutoPropertyAccessor, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator) { _property = property; _isAutoPropertyAccessor = isAutoPropertyAccessor; Debug.Assert(!_property.IsExpressionBodied, "Cannot have accessors in expression bodied lightweight properties"); _isExpressionBodied = !hasBody && hasExpressionBody; _usesInit = usesInit; if (_usesInit) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInitOnlySetters, diagnostics, location); } bool modifierErrors; var declarationModifiers = this.MakeModifiers(modifiers, property.IsExplicitInterfaceImplementation, hasBody || hasExpressionBody, location, diagnostics, out modifierErrors); // Include some modifiers from the containing property, but not the accessibility modifiers. declarationModifiers |= GetAccessorModifiers(propertyModifiers) & ~DeclarationModifiers.AccessibilityMask; if ((declarationModifiers & DeclarationModifiers.Private) != 0) { // Private accessors cannot be virtual. declarationModifiers &= ~DeclarationModifiers.Virtual; } // ReturnsVoid property is overridden in this class so // returnsVoid argument to MakeFlags is ignored. this.MakeFlags(methodKind, declarationModifiers, returnsVoid: false, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: property.IsExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody: hasBody || hasExpressionBody || isAutoPropertyAccessor, diagnostics); if (hasBody || hasExpressionBody) { CheckModifiersForBody(location, diagnostics); } var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, property.IsExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } if (!modifierErrors) { this.CheckModifiers(location, hasBody || hasExpressionBody, isAutoPropertyAccessor, diagnostics); } } #nullable disable private static DeclarationModifiers GetAccessorModifiers(DeclarationModifiers propertyModifiers) => propertyModifiers & ~(DeclarationModifiers.Indexer | DeclarationModifiers.ReadOnly); protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) { // These values may not be final, but we need to have something set here in the // event that we need to find the overridden accessor. _lazyParameters = ComputeParameters(diagnostics); _lazyReturnType = ComputeReturnType(diagnostics); _lazyRefCustomModifiers = ImmutableArray<CustomModifier>.Empty; var explicitInterfaceImplementations = ExplicitInterfaceImplementations; if (explicitInterfaceImplementations.Length > 0) { Debug.Assert(explicitInterfaceImplementations.Length == 1); MethodSymbol implementedMethod = explicitInterfaceImplementations[0]; CustomModifierUtils.CopyMethodCustomModifiers(implementedMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: false); } else if (this.IsOverride) { // This will cause another call to SourceMethodSymbol.LazyMethodChecks, // but that method already handles reentrancy for exactly this case. MethodSymbol overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { CustomModifierUtils.CopyMethodCustomModifiers(overriddenMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: true); } } else if (!_lazyReturnType.IsVoidType()) { PropertySymbol associatedProperty = _property; var type = associatedProperty.TypeWithAnnotations; _lazyReturnType = _lazyReturnType.WithTypeAndModifiers( CustomModifierUtils.CopyTypeCustomModifiers(type.Type, _lazyReturnType.Type, this.ContainingAssembly), type.CustomModifiers); _lazyRefCustomModifiers = associatedProperty.RefCustomModifiers; } } public sealed override Accessibility DeclaredAccessibility { get { var accessibility = this.LocalAccessibility; if (accessibility != Accessibility.NotApplicable) { return accessibility; } var propertyAccessibility = _property.DeclaredAccessibility; Debug.Assert(propertyAccessibility != Accessibility.NotApplicable); return propertyAccessibility; } } public sealed override Symbol AssociatedSymbol { get { return _property; } } public sealed override bool IsVararg { get { return false; } } public sealed override bool ReturnsVoid { get { return this.ReturnType.IsVoidType(); } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { LazyMethodChecks(); return _lazyParameters; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public sealed override RefKind RefKind { get { return _property.RefKind; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { LazyMethodChecks(); return _lazyReturnType; } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations { get { if (MethodKind == MethodKind.PropertySet) { return FlowAnalysisAnnotations.None; } var result = FlowAnalysisAnnotations.None; if (_property.HasMaybeNull) { result |= FlowAnalysisAnnotations.MaybeNull; } if (_property.HasNotNull) { result |= FlowAnalysisAnnotations.NotNull; } return result; } } public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; private TypeWithAnnotations ComputeReturnType(BindingDiagnosticBag diagnostics) { if (this.MethodKind == MethodKind.PropertyGet) { var type = _property.TypeWithAnnotations; if (type.Type.IsStatic) { // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), this.locations[0], type.Type); } return type; } else { var binder = GetBinder(); var type = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_Void, diagnostics, this.GetSyntax())); if (IsInitOnly) { var isInitOnlyType = Binder.GetWellKnownType(this.DeclaringCompilation, WellKnownType.System_Runtime_CompilerServices_IsExternalInit, diagnostics, this.locations[0]); var modifiers = ImmutableArray.Create<CustomModifier>( CSharpCustomModifier.CreateRequired(isInitOnlyType)); type = type.WithModifiers(modifiers); } return type; } } private Binder GetBinder() { var syntax = this.GetSyntax(); var compilation = this.DeclaringCompilation; var binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree); return binderFactory.GetBinder(syntax); } public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { LazyMethodChecks(); return _lazyRefCustomModifiers; } } /// <summary> /// Return Accessibility declared locally on the accessor, or /// NotApplicable if no accessibility was declared explicitly. /// </summary> internal Accessibility LocalAccessibility { get { return ModifierUtils.EffectiveAccessibility(this.DeclarationModifiers); } } /// <summary> /// Indicates whether this accessor itself has a 'readonly' modifier. /// </summary> internal bool LocalDeclaredReadOnly => (DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; /// <summary> /// Indicates whether this accessor is readonly due to reasons scoped to itself and its containing property. /// </summary> internal sealed override bool IsDeclaredReadOnly { get { if (LocalDeclaredReadOnly || (_property.HasReadOnlyModifier && IsValidReadOnlyTarget)) { return true; } // The below checks are used to decide if this accessor is implicitly 'readonly'. // Making a member implicitly 'readonly' allows valid C# 7.0 code to break PEVerify. // For instance: // struct S { // int Value { get; set; } // static readonly S StaticField = new S(); // static void M() { // System.Console.WriteLine(StaticField.Value); // } // } // The above program will fail PEVerify if the 'S.Value.get' accessor is made implicitly readonly because // we won't emit an implicit copy of 'S.StaticField' to pass to 'S.Value.get'. // Code emitted in C# 7.0 and before must be PEVerify compatible, so we will only make // members implicitly readonly in language versions which support the readonly members feature. var options = (CSharpParseOptions)SyntaxTree.Options; if (!options.IsFeatureEnabled(MessageID.IDS_FeatureReadOnlyMembers)) { return false; } // If we have IsReadOnly..ctor, we can use the attribute. Otherwise, we need to NOT be a netmodule and the type must not already exist in order to synthesize it. var isReadOnlyAttributeUsable = DeclaringCompilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor) != null || (DeclaringCompilation.Options.OutputKind != OutputKind.NetModule && DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute) is MissingMetadataTypeSymbol); if (!isReadOnlyAttributeUsable) { // if the readonly attribute isn't usable, don't implicitly make auto-getters readonly. return false; } return ContainingType.IsStructType() && !_property.IsStatic && _isAutoPropertyAccessor && MethodKind == MethodKind.PropertyGet; } } internal sealed override bool IsInitOnly => !IsStatic && _usesInit; private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, bool isExplicitInterfaceImplementation, bool hasBody, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) { // No default accessibility. If unset, accessibility // will be inherited from the property. const DeclarationModifiers defaultAccess = DeclarationModifiers.None; // Check that the set of modifiers is allowed var allowedModifiers = isExplicitInterfaceImplementation ? DeclarationModifiers.None : DeclarationModifiers.AccessibilityMask; if (this.ContainingType.IsStructType()) { allowedModifiers |= DeclarationModifiers.ReadOnly; } var defaultInterfaceImplementationModifiers = DeclarationModifiers.None; if (this.ContainingType.IsInterface && !isExplicitInterfaceImplementation) { defaultInterfaceImplementationModifiers = DeclarationModifiers.AccessibilityMask; } var mods = ModifierUtils.MakeAndCheckNontypeMemberModifiers(modifiers, defaultAccess, allowedModifiers, location, diagnostics, out modifierErrors); ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods, defaultInterfaceImplementationModifiers, location, diagnostics); return mods; } private void CheckModifiers(Location location, bool hasBody, bool isAutoPropertyOrExpressionBodied, BindingDiagnosticBag diagnostics) { // Check accessibility against the accessibility declared on the accessor not the property. var localAccessibility = this.LocalAccessibility; if (IsAbstract && !ContainingType.IsAbstract && (ContainingType.TypeKind == TypeKind.Class || ContainingType.TypeKind == TypeKind.Submission)) { // '{0}' is abstract but it is contained in non-abstract type '{1}' diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); } else if (IsVirtual && ContainingType.IsSealed && ContainingType.TypeKind != TypeKind.Struct) // error CS0106 on struct already { // '{0}' is a new virtual member in sealed type '{1}' diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); } else if (!hasBody && !IsExtern && !IsAbstract && !isAutoPropertyOrExpressionBodied) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } else if (ContainingType.IsSealed && localAccessibility.HasProtected() && !this.IsOverride) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } else if (LocalDeclaredReadOnly && _property.HasReadOnlyModifier) { // Cannot specify 'readonly' modifiers on both property or indexer '{0}' and its accessors. diagnostics.Add(ErrorCode.ERR_InvalidPropertyReadOnlyMods, location, _property); } else if (LocalDeclaredReadOnly && IsStatic) { // Static member '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); } else if (LocalDeclaredReadOnly && IsInitOnly) { // 'init' accessors cannot be marked 'readonly'. Mark '{0}' readonly instead. diagnostics.Add(ErrorCode.ERR_InitCannotBeReadonly, location, _property); } else if (LocalDeclaredReadOnly && _isAutoPropertyAccessor && MethodKind == MethodKind.PropertySet) { // Auto-implemented accessor '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_AutoSetterCantBeReadOnly, location, this); } else if (_usesInit && IsStatic) { // The 'init' accessor is not valid on static members diagnostics.Add(ErrorCode.ERR_BadInitAccessor, location); } } /// <summary> /// If we are outputting a .winmdobj then the setter name is put_, not set_. /// </summary> internal static string GetAccessorName(string propertyName, bool getNotSet, bool isWinMdOutput) { var prefix = getNotSet ? "get_" : isWinMdOutput ? "put_" : "set_"; return prefix + propertyName; } /// <returns> /// The declaring syntax for the accessor, or property if there is no accessor-specific /// syntax. /// </returns> internal CSharpSyntaxNode GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax(); } internal sealed override bool IsExplicitInterfaceImplementation { get { return _property.IsExplicitInterfaceImplementation; } } #nullable enable public sealed override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { PropertySymbol? explicitlyImplementedPropertyOpt = IsExplicitInterfaceImplementation ? _property.ExplicitInterfaceImplementations.FirstOrDefault() : null; ImmutableArray<MethodSymbol> explicitInterfaceImplementations; if (explicitlyImplementedPropertyOpt is null) { explicitInterfaceImplementations = ImmutableArray<MethodSymbol>.Empty; } else { MethodSymbol implementedAccessor = this.MethodKind == MethodKind.PropertyGet ? explicitlyImplementedPropertyOpt.GetMethod : explicitlyImplementedPropertyOpt.SetMethod; explicitInterfaceImplementations = (object)implementedAccessor == null ? ImmutableArray<MethodSymbol>.Empty : ImmutableArray.Create<MethodSymbol>(implementedAccessor); } ImmutableInterlocked.InterlockedInitialize(ref _lazyExplicitInterfaceImplementations, explicitInterfaceImplementations); } return _lazyExplicitInterfaceImplementations; } } #nullable disable internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { var syntax = this.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return OneOrMany.Create(((AccessorDeclarationSyntax)syntax).AttributeLists); } return base.GetAttributeDeclarations(); } #nullable enable public sealed override string Name { get { if (_lazyName is null) { bool isGetMethod = this.MethodKind == MethodKind.PropertyGet; string? name = null; if (IsExplicitInterfaceImplementation) { PropertySymbol? explicitlyImplementedPropertyOpt = _property.ExplicitInterfaceImplementations.FirstOrDefault(); if (explicitlyImplementedPropertyOpt is object) { MethodSymbol? implementedAccessor = isGetMethod ? explicitlyImplementedPropertyOpt.GetMethod : explicitlyImplementedPropertyOpt.SetMethod; string accessorName = (object)implementedAccessor != null ? implementedAccessor.Name : GetAccessorName(explicitlyImplementedPropertyOpt.MetadataName, isGetMethod, isWinMdOutput: _property.IsCompilationOutputWinMdObj()); //Not name - could be indexer placeholder string? aliasQualifierOpt = _property.GetExplicitInterfaceSpecifier()?.Name.GetAliasQualifierOpt(); name = ExplicitInterfaceHelpers.GetMemberName(accessorName, explicitlyImplementedPropertyOpt.ContainingType, aliasQualifierOpt); } } else if (IsOverride) { MethodSymbol overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { // If this accessor is overriding a method from metadata, it is possible that // the name of the overridden method doesn't follow the C# get_X/set_X pattern. // We should copy the name so that the runtime will recognize this as an override. name = overriddenMethod.Name; } } if (name is null) { name = GetAccessorName(_property.SourceName, isGetMethod, isWinMdOutput: _property.IsCompilationOutputWinMdObj()); } InterlockedOperations.Initialize(ref _lazyName, name); } return _lazyName; } } #nullable disable public sealed override bool IsImplicitlyDeclared { get { // Per design meeting resolution [see bug 11253], no source accessor is implicitly declared in C#, // if there is "get", "set", or expression-body syntax. switch (GetSyntax().Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.ArrowExpressionClause: return false; }; return true; } } internal sealed override bool GenerateDebugInfo { get { return true; } } public sealed override bool AreLocalsZeroed { get { return !_property.HasSkipLocalsInitAttribute && base.AreLocalsZeroed; } } private ImmutableArray<ParameterSymbol> ComputeParameters(BindingDiagnosticBag diagnostics) { bool isGetMethod = this.MethodKind == MethodKind.PropertyGet; var propertyParameters = _property.Parameters; int nPropertyParameters = propertyParameters.Length; int nParameters = nPropertyParameters + (isGetMethod ? 0 : 1); if (nParameters == 0) { return ImmutableArray<ParameterSymbol>.Empty; } var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(nParameters); // Clone the property parameters for the accessor method. The // parameters are cloned (rather than referenced from the property) // since the ContainingSymbol needs to be set to the accessor. foreach (SourceParameterSymbol propertyParam in propertyParameters) { parameters.Add(new SourceClonedParameterSymbol(propertyParam, this, propertyParam.Ordinal, suppressOptional: false)); } if (!isGetMethod) { var propertyType = _property.TypeWithAnnotations; if (propertyType.IsStatic) { // '{0}': static types cannot be used as parameters diagnostics.Add(ErrorFacts.GetStaticClassParameterCode(ContainingType.IsInterfaceType()), this.locations[0], propertyType.Type); } parameters.Add(new SynthesizedAccessorValueParameterSymbol(this, propertyType, parameters.Count)); } return parameters.ToImmutableAndFree(); } internal sealed override void AddSynthesizedReturnTypeAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedReturnTypeAttributes(moduleBuilder, ref attributes); var annotations = ReturnTypeFlowAnalysisAnnotations; if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(_property.MaybeNullAttributeIfExists)); } if ((annotations & FlowAnalysisAnnotations.NotNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(_property.NotNullAttributeIfExists)); } } internal sealed override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (_isAutoPropertyAccessor) { var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } if (!NotNullMembers.IsEmpty) { foreach (var attributeData in _property.MemberNotNullAttributeIfExists) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(attributeData)); } } if (!NotNullWhenTrueMembers.IsEmpty || !NotNullWhenFalseMembers.IsEmpty) { foreach (var attributeData in _property.MemberNotNullWhenAttributeIfExists) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(attributeData)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class SourcePropertyAccessorSymbol : SourceMemberMethodSymbol { private readonly SourcePropertySymbolBase _property; private ImmutableArray<ParameterSymbol> _lazyParameters; private TypeWithAnnotations _lazyReturnType; private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; private ImmutableArray<MethodSymbol> _lazyExplicitInterfaceImplementations; private string _lazyName; private readonly bool _isAutoPropertyAccessor; private readonly bool _isExpressionBodied; private readonly bool _usesInit; public static SourcePropertyAccessorSymbol CreateAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, AccessorDeclarationSyntax syntax, bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax.Kind() == SyntaxKind.GetAccessorDeclaration || syntax.Kind() == SyntaxKind.SetAccessorDeclaration || syntax.Kind() == SyntaxKind.InitAccessorDeclaration); bool isGetMethod = (syntax.Kind() == SyntaxKind.GetAccessorDeclaration); var methodKind = isGetMethod ? MethodKind.PropertyGet : MethodKind.PropertySet; bool hasBody = syntax.Body is object; bool hasExpressionBody = syntax.ExpressionBody is object; bool isNullableAnalysisEnabled = containingType.DeclaringCompilation.IsNullableAnalysisEnabledIn(syntax); CheckForBlockAndExpressionBody(syntax.Body, syntax.ExpressionBody, syntax, diagnostics); return new SourcePropertyAccessorSymbol( containingType, property, propertyModifiers, syntax.Keyword.GetLocation(), syntax, hasBody, hasExpressionBody, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), syntax.Modifiers, methodKind, syntax.Keyword.IsKind(SyntaxKind.InitKeyword), isAutoPropertyAccessor, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics); } public static SourcePropertyAccessorSymbol CreateAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, ArrowExpressionClauseSyntax syntax, BindingDiagnosticBag diagnostics) { bool isNullableAnalysisEnabled = containingType.DeclaringCompilation.IsNullableAnalysisEnabledIn(syntax); return new SourcePropertyAccessorSymbol( containingType, property, propertyModifiers, syntax.Expression.GetLocation(), syntax, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics); } #nullable enable public static SourcePropertyAccessorSymbol CreateAccessorSymbol( bool isGetMethod, bool usesInit, NamedTypeSymbol containingType, SynthesizedRecordPropertySymbol property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { var methodKind = isGetMethod ? MethodKind.PropertyGet : MethodKind.PropertySet; return new SourcePropertyAccessorSymbol( containingType, property, propertyModifiers, location, syntax, hasBody: false, hasExpressionBody: false, isIterator: false, modifiers: new SyntaxTokenList(), methodKind, usesInit, isAutoPropertyAccessor: true, isNullableAnalysisEnabled: false, diagnostics); } public static SourcePropertyAccessorSymbol CreateAccessorSymbol( NamedTypeSymbol containingType, SynthesizedRecordEqualityContractProperty property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { return new SynthesizedRecordEqualityContractProperty.GetAccessorSymbol( containingType, property, propertyModifiers, location, syntax, diagnostics); } #nullable disable internal sealed override bool IsExpressionBodied => _isExpressionBodied; internal sealed override ImmutableArray<string> NotNullMembers => _property.NotNullMembers.Concat(base.NotNullMembers); internal sealed override ImmutableArray<string> NotNullWhenTrueMembers => _property.NotNullWhenTrueMembers.Concat(base.NotNullWhenTrueMembers); internal sealed override ImmutableArray<string> NotNullWhenFalseMembers => _property.NotNullWhenFalseMembers.Concat(base.NotNullWhenFalseMembers); private SourcePropertyAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbol property, DeclarationModifiers propertyModifiers, Location location, ArrowExpressionClauseSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: false) { _property = property; _isAutoPropertyAccessor = false; _isExpressionBodied = true; // The modifiers for the accessor are the same as the modifiers for the property, // minus the indexer and readonly bit var declarationModifiers = GetAccessorModifiers(propertyModifiers); // ReturnsVoid property is overridden in this class so // returnsVoid argument to MakeFlags is ignored. this.MakeFlags(MethodKind.PropertyGet, declarationModifiers, returnsVoid: false, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: property.IsExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody: true, diagnostics: diagnostics); CheckModifiersForBody(location, diagnostics); var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, property.IsExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } this.CheckModifiers(location, hasBody: true, isAutoPropertyOrExpressionBodied: true, diagnostics: diagnostics); } #nullable enable protected SourcePropertyAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, bool hasBody, bool hasExpressionBody, bool isIterator, SyntaxTokenList modifiers, MethodKind methodKind, bool usesInit, bool isAutoPropertyAccessor, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator) { _property = property; _isAutoPropertyAccessor = isAutoPropertyAccessor; Debug.Assert(!_property.IsExpressionBodied, "Cannot have accessors in expression bodied lightweight properties"); _isExpressionBodied = !hasBody && hasExpressionBody; _usesInit = usesInit; if (_usesInit) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInitOnlySetters, diagnostics, location); } bool modifierErrors; var declarationModifiers = this.MakeModifiers(modifiers, property.IsExplicitInterfaceImplementation, hasBody || hasExpressionBody, location, diagnostics, out modifierErrors); // Include some modifiers from the containing property, but not the accessibility modifiers. declarationModifiers |= GetAccessorModifiers(propertyModifiers) & ~DeclarationModifiers.AccessibilityMask; if ((declarationModifiers & DeclarationModifiers.Private) != 0) { // Private accessors cannot be virtual. declarationModifiers &= ~DeclarationModifiers.Virtual; } // ReturnsVoid property is overridden in this class so // returnsVoid argument to MakeFlags is ignored. this.MakeFlags(methodKind, declarationModifiers, returnsVoid: false, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: property.IsExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody: hasBody || hasExpressionBody || isAutoPropertyAccessor, diagnostics); if (hasBody || hasExpressionBody) { CheckModifiersForBody(location, diagnostics); } var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, property.IsExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } if (!modifierErrors) { this.CheckModifiers(location, hasBody || hasExpressionBody, isAutoPropertyAccessor, diagnostics); } } #nullable disable private static DeclarationModifiers GetAccessorModifiers(DeclarationModifiers propertyModifiers) => propertyModifiers & ~(DeclarationModifiers.Indexer | DeclarationModifiers.ReadOnly); protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) { // These values may not be final, but we need to have something set here in the // event that we need to find the overridden accessor. _lazyParameters = ComputeParameters(diagnostics); _lazyReturnType = ComputeReturnType(diagnostics); _lazyRefCustomModifiers = ImmutableArray<CustomModifier>.Empty; var explicitInterfaceImplementations = ExplicitInterfaceImplementations; if (explicitInterfaceImplementations.Length > 0) { Debug.Assert(explicitInterfaceImplementations.Length == 1); MethodSymbol implementedMethod = explicitInterfaceImplementations[0]; CustomModifierUtils.CopyMethodCustomModifiers(implementedMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: false); } else if (this.IsOverride) { // This will cause another call to SourceMethodSymbol.LazyMethodChecks, // but that method already handles reentrancy for exactly this case. MethodSymbol overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { CustomModifierUtils.CopyMethodCustomModifiers(overriddenMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: true); } } else if (!_lazyReturnType.IsVoidType()) { PropertySymbol associatedProperty = _property; var type = associatedProperty.TypeWithAnnotations; _lazyReturnType = _lazyReturnType.WithTypeAndModifiers( CustomModifierUtils.CopyTypeCustomModifiers(type.Type, _lazyReturnType.Type, this.ContainingAssembly), type.CustomModifiers); _lazyRefCustomModifiers = associatedProperty.RefCustomModifiers; } } public sealed override Accessibility DeclaredAccessibility { get { var accessibility = this.LocalAccessibility; if (accessibility != Accessibility.NotApplicable) { return accessibility; } var propertyAccessibility = _property.DeclaredAccessibility; Debug.Assert(propertyAccessibility != Accessibility.NotApplicable); return propertyAccessibility; } } public sealed override Symbol AssociatedSymbol { get { return _property; } } public sealed override bool IsVararg { get { return false; } } public sealed override bool ReturnsVoid { get { return this.ReturnType.IsVoidType(); } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { LazyMethodChecks(); return _lazyParameters; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public sealed override RefKind RefKind { get { return _property.RefKind; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { LazyMethodChecks(); return _lazyReturnType; } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations { get { if (MethodKind == MethodKind.PropertySet) { return FlowAnalysisAnnotations.None; } var result = FlowAnalysisAnnotations.None; if (_property.HasMaybeNull) { result |= FlowAnalysisAnnotations.MaybeNull; } if (_property.HasNotNull) { result |= FlowAnalysisAnnotations.NotNull; } return result; } } public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; private TypeWithAnnotations ComputeReturnType(BindingDiagnosticBag diagnostics) { if (this.MethodKind == MethodKind.PropertyGet) { var type = _property.TypeWithAnnotations; if (type.Type.IsStatic) { // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), this.locations[0], type.Type); } return type; } else { var binder = GetBinder(); var type = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_Void, diagnostics, this.GetSyntax())); if (IsInitOnly) { var isInitOnlyType = Binder.GetWellKnownType(this.DeclaringCompilation, WellKnownType.System_Runtime_CompilerServices_IsExternalInit, diagnostics, this.locations[0]); var modifiers = ImmutableArray.Create<CustomModifier>( CSharpCustomModifier.CreateRequired(isInitOnlyType)); type = type.WithModifiers(modifiers); } return type; } } private Binder GetBinder() { var syntax = this.GetSyntax(); var compilation = this.DeclaringCompilation; var binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree); return binderFactory.GetBinder(syntax); } public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { LazyMethodChecks(); return _lazyRefCustomModifiers; } } /// <summary> /// Return Accessibility declared locally on the accessor, or /// NotApplicable if no accessibility was declared explicitly. /// </summary> internal Accessibility LocalAccessibility { get { return ModifierUtils.EffectiveAccessibility(this.DeclarationModifiers); } } /// <summary> /// Indicates whether this accessor itself has a 'readonly' modifier. /// </summary> internal bool LocalDeclaredReadOnly => (DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; /// <summary> /// Indicates whether this accessor is readonly due to reasons scoped to itself and its containing property. /// </summary> internal sealed override bool IsDeclaredReadOnly { get { if (LocalDeclaredReadOnly || (_property.HasReadOnlyModifier && IsValidReadOnlyTarget)) { return true; } // The below checks are used to decide if this accessor is implicitly 'readonly'. // Making a member implicitly 'readonly' allows valid C# 7.0 code to break PEVerify. // For instance: // struct S { // int Value { get; set; } // static readonly S StaticField = new S(); // static void M() { // System.Console.WriteLine(StaticField.Value); // } // } // The above program will fail PEVerify if the 'S.Value.get' accessor is made implicitly readonly because // we won't emit an implicit copy of 'S.StaticField' to pass to 'S.Value.get'. // Code emitted in C# 7.0 and before must be PEVerify compatible, so we will only make // members implicitly readonly in language versions which support the readonly members feature. var options = (CSharpParseOptions)SyntaxTree.Options; if (!options.IsFeatureEnabled(MessageID.IDS_FeatureReadOnlyMembers)) { return false; } // If we have IsReadOnly..ctor, we can use the attribute. Otherwise, we need to NOT be a netmodule and the type must not already exist in order to synthesize it. var isReadOnlyAttributeUsable = DeclaringCompilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor) != null || (DeclaringCompilation.Options.OutputKind != OutputKind.NetModule && DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute) is MissingMetadataTypeSymbol); if (!isReadOnlyAttributeUsable) { // if the readonly attribute isn't usable, don't implicitly make auto-getters readonly. return false; } return ContainingType.IsStructType() && !_property.IsStatic && _isAutoPropertyAccessor && MethodKind == MethodKind.PropertyGet; } } internal sealed override bool IsInitOnly => !IsStatic && _usesInit; private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, bool isExplicitInterfaceImplementation, bool hasBody, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) { // No default accessibility. If unset, accessibility // will be inherited from the property. const DeclarationModifiers defaultAccess = DeclarationModifiers.None; // Check that the set of modifiers is allowed var allowedModifiers = isExplicitInterfaceImplementation ? DeclarationModifiers.None : DeclarationModifiers.AccessibilityMask; if (this.ContainingType.IsStructType()) { allowedModifiers |= DeclarationModifiers.ReadOnly; } var defaultInterfaceImplementationModifiers = DeclarationModifiers.None; if (this.ContainingType.IsInterface && !isExplicitInterfaceImplementation) { defaultInterfaceImplementationModifiers = DeclarationModifiers.AccessibilityMask; } var mods = ModifierUtils.MakeAndCheckNontypeMemberModifiers(modifiers, defaultAccess, allowedModifiers, location, diagnostics, out modifierErrors); ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods, defaultInterfaceImplementationModifiers, location, diagnostics); return mods; } private void CheckModifiers(Location location, bool hasBody, bool isAutoPropertyOrExpressionBodied, BindingDiagnosticBag diagnostics) { // Check accessibility against the accessibility declared on the accessor not the property. var localAccessibility = this.LocalAccessibility; if (IsAbstract && !ContainingType.IsAbstract && (ContainingType.TypeKind == TypeKind.Class || ContainingType.TypeKind == TypeKind.Submission)) { // '{0}' is abstract but it is contained in non-abstract type '{1}' diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); } else if (IsVirtual && ContainingType.IsSealed && ContainingType.TypeKind != TypeKind.Struct) // error CS0106 on struct already { // '{0}' is a new virtual member in sealed type '{1}' diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); } else if (!hasBody && !IsExtern && !IsAbstract && !isAutoPropertyOrExpressionBodied) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } else if (ContainingType.IsSealed && localAccessibility.HasProtected() && !this.IsOverride) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } else if (LocalDeclaredReadOnly && _property.HasReadOnlyModifier) { // Cannot specify 'readonly' modifiers on both property or indexer '{0}' and its accessors. diagnostics.Add(ErrorCode.ERR_InvalidPropertyReadOnlyMods, location, _property); } else if (LocalDeclaredReadOnly && IsStatic) { // Static member '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); } else if (LocalDeclaredReadOnly && IsInitOnly) { // 'init' accessors cannot be marked 'readonly'. Mark '{0}' readonly instead. diagnostics.Add(ErrorCode.ERR_InitCannotBeReadonly, location, _property); } else if (LocalDeclaredReadOnly && _isAutoPropertyAccessor && MethodKind == MethodKind.PropertySet) { // Auto-implemented accessor '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_AutoSetterCantBeReadOnly, location, this); } else if (_usesInit && IsStatic) { // The 'init' accessor is not valid on static members diagnostics.Add(ErrorCode.ERR_BadInitAccessor, location); } } /// <summary> /// If we are outputting a .winmdobj then the setter name is put_, not set_. /// </summary> internal static string GetAccessorName(string propertyName, bool getNotSet, bool isWinMdOutput) { var prefix = getNotSet ? "get_" : isWinMdOutput ? "put_" : "set_"; return prefix + propertyName; } /// <returns> /// The declaring syntax for the accessor, or property if there is no accessor-specific /// syntax. /// </returns> internal CSharpSyntaxNode GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax(); } internal sealed override bool IsExplicitInterfaceImplementation { get { return _property.IsExplicitInterfaceImplementation; } } #nullable enable public sealed override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { PropertySymbol? explicitlyImplementedPropertyOpt = IsExplicitInterfaceImplementation ? _property.ExplicitInterfaceImplementations.FirstOrDefault() : null; ImmutableArray<MethodSymbol> explicitInterfaceImplementations; if (explicitlyImplementedPropertyOpt is null) { explicitInterfaceImplementations = ImmutableArray<MethodSymbol>.Empty; } else { MethodSymbol implementedAccessor = this.MethodKind == MethodKind.PropertyGet ? explicitlyImplementedPropertyOpt.GetMethod : explicitlyImplementedPropertyOpt.SetMethod; explicitInterfaceImplementations = (object)implementedAccessor == null ? ImmutableArray<MethodSymbol>.Empty : ImmutableArray.Create<MethodSymbol>(implementedAccessor); } ImmutableInterlocked.InterlockedInitialize(ref _lazyExplicitInterfaceImplementations, explicitInterfaceImplementations); } return _lazyExplicitInterfaceImplementations; } } #nullable disable internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { var syntax = this.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return OneOrMany.Create(((AccessorDeclarationSyntax)syntax).AttributeLists); } return base.GetAttributeDeclarations(); } #nullable enable public sealed override string Name { get { if (_lazyName is null) { bool isGetMethod = this.MethodKind == MethodKind.PropertyGet; string? name = null; if (IsExplicitInterfaceImplementation) { PropertySymbol? explicitlyImplementedPropertyOpt = _property.ExplicitInterfaceImplementations.FirstOrDefault(); if (explicitlyImplementedPropertyOpt is object) { MethodSymbol? implementedAccessor = isGetMethod ? explicitlyImplementedPropertyOpt.GetMethod : explicitlyImplementedPropertyOpt.SetMethod; string accessorName = (object)implementedAccessor != null ? implementedAccessor.Name : GetAccessorName(explicitlyImplementedPropertyOpt.MetadataName, isGetMethod, isWinMdOutput: _property.IsCompilationOutputWinMdObj()); //Not name - could be indexer placeholder string? aliasQualifierOpt = _property.GetExplicitInterfaceSpecifier()?.Name.GetAliasQualifierOpt(); name = ExplicitInterfaceHelpers.GetMemberName(accessorName, explicitlyImplementedPropertyOpt.ContainingType, aliasQualifierOpt); } } else if (IsOverride) { MethodSymbol overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { // If this accessor is overriding a method from metadata, it is possible that // the name of the overridden method doesn't follow the C# get_X/set_X pattern. // We should copy the name so that the runtime will recognize this as an override. name = overriddenMethod.Name; } } if (name is null) { name = GetAccessorName(_property.SourceName, isGetMethod, isWinMdOutput: _property.IsCompilationOutputWinMdObj()); } InterlockedOperations.Initialize(ref _lazyName, name); } return _lazyName; } } #nullable disable public sealed override bool IsImplicitlyDeclared { get { // Per design meeting resolution [see bug 11253], no source accessor is implicitly declared in C#, // if there is "get", "set", or expression-body syntax. switch (GetSyntax().Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.ArrowExpressionClause: return false; }; return true; } } internal sealed override bool GenerateDebugInfo { get { return true; } } public sealed override bool AreLocalsZeroed { get { return !_property.HasSkipLocalsInitAttribute && base.AreLocalsZeroed; } } private ImmutableArray<ParameterSymbol> ComputeParameters(BindingDiagnosticBag diagnostics) { bool isGetMethod = this.MethodKind == MethodKind.PropertyGet; var propertyParameters = _property.Parameters; int nPropertyParameters = propertyParameters.Length; int nParameters = nPropertyParameters + (isGetMethod ? 0 : 1); if (nParameters == 0) { return ImmutableArray<ParameterSymbol>.Empty; } var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(nParameters); // Clone the property parameters for the accessor method. The // parameters are cloned (rather than referenced from the property) // since the ContainingSymbol needs to be set to the accessor. foreach (SourceParameterSymbol propertyParam in propertyParameters) { parameters.Add(new SourceClonedParameterSymbol(propertyParam, this, propertyParam.Ordinal, suppressOptional: false)); } if (!isGetMethod) { var propertyType = _property.TypeWithAnnotations; if (propertyType.IsStatic) { // '{0}': static types cannot be used as parameters diagnostics.Add(ErrorFacts.GetStaticClassParameterCode(ContainingType.IsInterfaceType()), this.locations[0], propertyType.Type); } parameters.Add(new SynthesizedAccessorValueParameterSymbol(this, propertyType, parameters.Count)); } return parameters.ToImmutableAndFree(); } internal sealed override void AddSynthesizedReturnTypeAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedReturnTypeAttributes(moduleBuilder, ref attributes); var annotations = ReturnTypeFlowAnalysisAnnotations; if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(_property.MaybeNullAttributeIfExists)); } if ((annotations & FlowAnalysisAnnotations.NotNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(_property.NotNullAttributeIfExists)); } } internal sealed override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (_isAutoPropertyAccessor) { var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } if (!NotNullMembers.IsEmpty) { foreach (var attributeData in _property.MemberNotNullAttributeIfExists) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(attributeData)); } } if (!NotNullWhenTrueMembers.IsEmpty || !NotNullWhenFalseMembers.IsEmpty) { foreach (var attributeData in _property.MemberNotNullWhenAttributeIfExists) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(attributeData)); } } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CoreTest/Differencing/LongestCommonSubsequenceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; using Xunit; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Differencing.UnitTests { public class LongestCommonSubsequenceTests { private readonly LongestCommonSubsequenceString lcs = new LongestCommonSubsequenceString(); private class LongestCommonSubsequenceString : LongestCommonSubsequence<string> { protected override bool ItemsEqual(string oldSequence, int oldIndex, string newSequence, int newIndex) => oldSequence[oldIndex] == newSequence[newIndex]; public IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(string oldSequence, string newSequence) => GetMatchingPairs(oldSequence, oldSequence.Length, newSequence, newSequence.Length); public IEnumerable<SequenceEdit> GetEdits(string oldSequence, string newSequence) => GetEdits(oldSequence, oldSequence.Length, newSequence, newSequence.Length); public double ComputeDistance(string oldSequence, string newSequence) => ComputeDistance(oldSequence, oldSequence.Length, newSequence, newSequence.Length); } private static void VerifyMatchingPairs(IEnumerable<KeyValuePair<int, int>> actualPairs, string expectedPairsStr) { var sb = new StringBuilder(expectedPairsStr.Length); foreach (var actPair in actualPairs) { sb.AppendFormat("[{0},{1}]", actPair.Key, actPair.Value); } var actualPairsStr = sb.ToString(); Assert.Equal(expectedPairsStr, actualPairsStr); } private static void VerifyEdits(string oldStr, string newStr, IEnumerable<SequenceEdit> edits) { var oldChars = oldStr.ToCharArray(); var newChars = new char[newStr.Length]; foreach (var edit in edits) { Assert.True(edit.Kind == EditKind.Delete || edit.Kind == EditKind.Insert || edit.Kind == EditKind.Update); switch (edit.Kind) { case EditKind.Delete: Assert.True(edit.OldIndex < oldStr.Length); oldChars[edit.OldIndex] = '\0'; break; case EditKind.Insert: Assert.True(edit.NewIndex < newStr.Length); newChars[edit.NewIndex] = newStr[edit.NewIndex]; break; case EditKind.Update: Assert.True(edit.OldIndex < oldStr.Length); Assert.True(edit.NewIndex < newStr.Length); newChars[edit.NewIndex] = oldStr[edit.OldIndex]; oldChars[edit.OldIndex] = '\0'; break; } } var editedStr = new String(newChars); Assert.Equal(editedStr, newStr); Array.ForEach(oldChars, (c) => { Assert.Equal('\0', c); }); } [Fact] public void EmptyStrings() { var str1 = ""; var str2 = ""; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertToEmpty() { var str1 = ""; var str2 = "ABC"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(1.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertAtBeginning() { var str1 = "ABC"; var str2 = "XYZABC"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,5][1,4][0,3]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertAtEnd() { var str1 = "ABC"; var str2 = "ABCXYZ"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,2][1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertInMidlle() { var str1 = "ABC"; var str2 = "ABXYC"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,4][1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.4, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteToEmpty() { var str1 = "ABC"; var str2 = ""; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(1.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteAtBeginning() { var str1 = "ABCD"; var str2 = "C"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.75, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteAtEnd() { var str1 = "ABCD"; var str2 = "AB"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteInMiddle() { var str1 = "ABCDE"; var str2 = "ADE"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[4,2][3,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.4, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceAll() { var str1 = "ABC"; var str2 = "XYZ"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(1.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceAtBeginning() { var str1 = "ABCD"; var str2 = "XYD"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[3,2]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.75, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceAtEnd() { var str1 = "ABCD"; var str2 = "ABXYZ"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.6, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceInMiddle() { var str1 = "ABCDE"; var str2 = "AXDE"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[4,3][3,2][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.4, lcs.ComputeDistance(str1, str2)); } [Fact] public void Combination1() { var str1 = "ABBCDEFIJ"; var str2 = "AABDEEGH"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[5,4][4,3][1,2][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.556, lcs.ComputeDistance(str1, str2), precision: 3); } [Fact] public void Combination2() { var str1 = "AAABBCCDDD"; var str2 = "ABXCD"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[7,4][5,3][3,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.6, lcs.ComputeDistance(str1, str2)); } [Fact] public void Combination3() { var str1 = "ABCABBA"; var str2 = "CBABAC"; // 2 possible matches: // "[6,4][4,3][3,2][1,1]" <- this one is backwards compatible // "[6,4][4,3][3,2][2,0]" VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[6,4][4,3][3,2][1,1]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.429, lcs.ComputeDistance(str1, str2), precision: 3); } [Fact] public void Reorder1() { var str1 = "AB"; var str2 = "BA"; // 2 possible matches: // "[0,1]" <- this one is backwards compatible // "[1,0]" VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[0,1]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void LongString() { var s = "A"; var x9 = new string('x', 9); var x10 = new string('x', 10); var x99 = new string('x', 99); var x1000 = new string('x', 1000); var y1000 = new string('y', 1000); var sx9 = s + x9; var sx99 = s + x99; var sx1000 = s + new string('x', 1000); var sx100000000 = s + new string('x', 100000000); Assert.Equal(0.900, lcs.ComputeDistance(s, sx9), precision: 3); Assert.Equal(0.990, lcs.ComputeDistance(s, sx99), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(s, sx1000), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(s, sx100000000), precision: 3); Assert.Equal(0.900, lcs.ComputeDistance(sx9, s), precision: 3); Assert.Equal(0.990, lcs.ComputeDistance(sx99, s), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(sx1000, s), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(sx100000000, s), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(x10 + y1000, x10), precision: 3); Assert.Equal(0.5, lcs.ComputeDistance(x1000 + y1000, x1000), precision: 3); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text; using Xunit; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Differencing.UnitTests { public class LongestCommonSubsequenceTests { private readonly LongestCommonSubsequenceString lcs = new LongestCommonSubsequenceString(); private class LongestCommonSubsequenceString : LongestCommonSubsequence<string> { protected override bool ItemsEqual(string oldSequence, int oldIndex, string newSequence, int newIndex) => oldSequence[oldIndex] == newSequence[newIndex]; public IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(string oldSequence, string newSequence) => GetMatchingPairs(oldSequence, oldSequence.Length, newSequence, newSequence.Length); public IEnumerable<SequenceEdit> GetEdits(string oldSequence, string newSequence) => GetEdits(oldSequence, oldSequence.Length, newSequence, newSequence.Length); public double ComputeDistance(string oldSequence, string newSequence) => ComputeDistance(oldSequence, oldSequence.Length, newSequence, newSequence.Length); } private static void VerifyMatchingPairs(IEnumerable<KeyValuePair<int, int>> actualPairs, string expectedPairsStr) { var sb = new StringBuilder(expectedPairsStr.Length); foreach (var actPair in actualPairs) { sb.AppendFormat("[{0},{1}]", actPair.Key, actPair.Value); } var actualPairsStr = sb.ToString(); Assert.Equal(expectedPairsStr, actualPairsStr); } private static void VerifyEdits(string oldStr, string newStr, IEnumerable<SequenceEdit> edits) { var oldChars = oldStr.ToCharArray(); var newChars = new char[newStr.Length]; foreach (var edit in edits) { Assert.True(edit.Kind == EditKind.Delete || edit.Kind == EditKind.Insert || edit.Kind == EditKind.Update); switch (edit.Kind) { case EditKind.Delete: Assert.True(edit.OldIndex < oldStr.Length); oldChars[edit.OldIndex] = '\0'; break; case EditKind.Insert: Assert.True(edit.NewIndex < newStr.Length); newChars[edit.NewIndex] = newStr[edit.NewIndex]; break; case EditKind.Update: Assert.True(edit.OldIndex < oldStr.Length); Assert.True(edit.NewIndex < newStr.Length); newChars[edit.NewIndex] = oldStr[edit.OldIndex]; oldChars[edit.OldIndex] = '\0'; break; } } var editedStr = new String(newChars); Assert.Equal(editedStr, newStr); Array.ForEach(oldChars, (c) => { Assert.Equal('\0', c); }); } [Fact] public void EmptyStrings() { var str1 = ""; var str2 = ""; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertToEmpty() { var str1 = ""; var str2 = "ABC"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(1.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertAtBeginning() { var str1 = "ABC"; var str2 = "XYZABC"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,5][1,4][0,3]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertAtEnd() { var str1 = "ABC"; var str2 = "ABCXYZ"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,2][1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void InsertInMidlle() { var str1 = "ABC"; var str2 = "ABXYC"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,4][1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.4, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteToEmpty() { var str1 = "ABC"; var str2 = ""; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(1.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteAtBeginning() { var str1 = "ABCD"; var str2 = "C"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[2,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.75, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteAtEnd() { var str1 = "ABCD"; var str2 = "AB"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void DeleteInMiddle() { var str1 = "ABCDE"; var str2 = "ADE"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[4,2][3,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.4, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceAll() { var str1 = "ABC"; var str2 = "XYZ"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), ""); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(1.0, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceAtBeginning() { var str1 = "ABCD"; var str2 = "XYD"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[3,2]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.75, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceAtEnd() { var str1 = "ABCD"; var str2 = "ABXYZ"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[1,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.6, lcs.ComputeDistance(str1, str2)); } [Fact] public void ReplaceInMiddle() { var str1 = "ABCDE"; var str2 = "AXDE"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[4,3][3,2][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.4, lcs.ComputeDistance(str1, str2)); } [Fact] public void Combination1() { var str1 = "ABBCDEFIJ"; var str2 = "AABDEEGH"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[5,4][4,3][1,2][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.556, lcs.ComputeDistance(str1, str2), precision: 3); } [Fact] public void Combination2() { var str1 = "AAABBCCDDD"; var str2 = "ABXCD"; VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[7,4][5,3][3,1][0,0]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.6, lcs.ComputeDistance(str1, str2)); } [Fact] public void Combination3() { var str1 = "ABCABBA"; var str2 = "CBABAC"; // 2 possible matches: // "[6,4][4,3][3,2][1,1]" <- this one is backwards compatible // "[6,4][4,3][3,2][2,0]" VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[6,4][4,3][3,2][1,1]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.429, lcs.ComputeDistance(str1, str2), precision: 3); } [Fact] public void Reorder1() { var str1 = "AB"; var str2 = "BA"; // 2 possible matches: // "[0,1]" <- this one is backwards compatible // "[1,0]" VerifyMatchingPairs(lcs.GetMatchingPairs(str1, str2), "[0,1]"); VerifyEdits(str1, str2, lcs.GetEdits(str1, str2)); Assert.Equal(0.5, lcs.ComputeDistance(str1, str2)); } [Fact] public void LongString() { var s = "A"; var x9 = new string('x', 9); var x10 = new string('x', 10); var x99 = new string('x', 99); var x1000 = new string('x', 1000); var y1000 = new string('y', 1000); var sx9 = s + x9; var sx99 = s + x99; var sx1000 = s + new string('x', 1000); var sx100000000 = s + new string('x', 100000000); Assert.Equal(0.900, lcs.ComputeDistance(s, sx9), precision: 3); Assert.Equal(0.990, lcs.ComputeDistance(s, sx99), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(s, sx1000), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(s, sx100000000), precision: 3); Assert.Equal(0.900, lcs.ComputeDistance(sx9, s), precision: 3); Assert.Equal(0.990, lcs.ComputeDistance(sx99, s), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(sx1000, s), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(sx100000000, s), precision: 3); Assert.Equal(1.000, lcs.ComputeDistance(x10 + y1000, x10), precision: 3); Assert.Equal(0.5, lcs.ComputeDistance(x1000 + y1000, x1000), precision: 3); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/AutomaticCompletion/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion { internal static class Extensions { /// <summary> /// create caret preserving edit transaction with automatic code change undo merging policy /// </summary> public static CaretPreservingEditTransaction CreateEditTransaction( this ITextView view, string description, ITextUndoHistoryRegistry registry, IEditorOperationsFactoryService service) { return new CaretPreservingEditTransaction(description, view, registry, service) { MergePolicy = AutomaticCodeChangeMergePolicy.Instance }; } public static SyntaxToken FindToken(this ITextSnapshot snapshot, int position, CancellationToken cancellationToken) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return default; } var root = document.GetSyntaxRootSynchronously(cancellationToken); return root.FindToken(position, findInsideTrivia: true); } /// <summary> /// insert text to workspace and get updated version of the document /// </summary> public static Document InsertText(this Document document, int position, string text, CancellationToken cancellationToken = default) => document.ReplaceText(new TextSpan(position, 0), text, cancellationToken); /// <summary> /// replace text to workspace and get updated version of the document /// </summary> public static Document ReplaceText(this Document document, TextSpan span, string text, CancellationToken cancellationToken) => document.ApplyTextChange(new TextChange(span, text), cancellationToken); /// <summary> /// apply text changes to workspace and get updated version of the document /// </summary> public static Document ApplyTextChange(this Document document, TextChange textChange, CancellationToken cancellationToken) => document.ApplyTextChanges(SpecializedCollections.SingletonEnumerable(textChange), cancellationToken); /// <summary> /// apply text changes to workspace and get updated version of the document /// </summary> public static Document ApplyTextChanges(this Document document, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken) { // here assumption is that text change are based on current solution var oldSolution = document.Project.Solution; var newSolution = oldSolution.UpdateDocument(document.Id, textChanges, cancellationToken); if (oldSolution.Workspace.TryApplyChanges(newSolution)) { return newSolution.Workspace.CurrentSolution.GetDocument(document.Id); } return document; } /// <summary> /// Update the solution so that the document with the Id has the text changes /// </summary> public static Solution UpdateDocument(this Solution solution, DocumentId id, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken = default) { var oldDocument = solution.GetDocument(id); var newText = oldDocument.GetTextSynchronously(cancellationToken).WithChanges(textChanges); return solution.WithDocumentText(id, newText); } public static SnapshotSpan GetSessionSpan(this IBraceCompletionSession session) { var snapshot = session.SubjectBuffer.CurrentSnapshot; var open = session.OpeningPoint.GetPoint(snapshot); var close = session.ClosingPoint.GetPoint(snapshot); return new SnapshotSpan(open, close); } public static SnapshotPoint? GetCaretPosition(this IBraceCompletionSession session) => GetCaretPoint(session, session.SubjectBuffer); // get the caret position within the given buffer private static SnapshotPoint? GetCaretPoint(this IBraceCompletionSession session, ITextBuffer buffer) => session.TextView.Caret.Position.Point.GetPoint(buffer, PositionAffinity.Predecessor); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion { internal static class Extensions { /// <summary> /// create caret preserving edit transaction with automatic code change undo merging policy /// </summary> public static CaretPreservingEditTransaction CreateEditTransaction( this ITextView view, string description, ITextUndoHistoryRegistry registry, IEditorOperationsFactoryService service) { return new CaretPreservingEditTransaction(description, view, registry, service) { MergePolicy = AutomaticCodeChangeMergePolicy.Instance }; } public static SyntaxToken FindToken(this ITextSnapshot snapshot, int position, CancellationToken cancellationToken) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return default; } var root = document.GetSyntaxRootSynchronously(cancellationToken); return root.FindToken(position, findInsideTrivia: true); } /// <summary> /// insert text to workspace and get updated version of the document /// </summary> public static Document InsertText(this Document document, int position, string text, CancellationToken cancellationToken = default) => document.ReplaceText(new TextSpan(position, 0), text, cancellationToken); /// <summary> /// replace text to workspace and get updated version of the document /// </summary> public static Document ReplaceText(this Document document, TextSpan span, string text, CancellationToken cancellationToken) => document.ApplyTextChange(new TextChange(span, text), cancellationToken); /// <summary> /// apply text changes to workspace and get updated version of the document /// </summary> public static Document ApplyTextChange(this Document document, TextChange textChange, CancellationToken cancellationToken) => document.ApplyTextChanges(SpecializedCollections.SingletonEnumerable(textChange), cancellationToken); /// <summary> /// apply text changes to workspace and get updated version of the document /// </summary> public static Document ApplyTextChanges(this Document document, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken) { // here assumption is that text change are based on current solution var oldSolution = document.Project.Solution; var newSolution = oldSolution.UpdateDocument(document.Id, textChanges, cancellationToken); if (oldSolution.Workspace.TryApplyChanges(newSolution)) { return newSolution.Workspace.CurrentSolution.GetDocument(document.Id); } return document; } /// <summary> /// Update the solution so that the document with the Id has the text changes /// </summary> public static Solution UpdateDocument(this Solution solution, DocumentId id, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken = default) { var oldDocument = solution.GetDocument(id); var newText = oldDocument.GetTextSynchronously(cancellationToken).WithChanges(textChanges); return solution.WithDocumentText(id, newText); } public static SnapshotSpan GetSessionSpan(this IBraceCompletionSession session) { var snapshot = session.SubjectBuffer.CurrentSnapshot; var open = session.OpeningPoint.GetPoint(snapshot); var close = session.ClosingPoint.GetPoint(snapshot); return new SnapshotSpan(open, close); } public static SnapshotPoint? GetCaretPosition(this IBraceCompletionSession session) => GetCaretPoint(session, session.SubjectBuffer); // get the caret position within the given buffer private static SnapshotPoint? GetCaretPoint(this IBraceCompletionSession session, ITextBuffer buffer) => session.TextView.Caret.Position.Point.GetPoint(buffer, PositionAffinity.Predecessor); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Diagnostics/InternalDiagnosticsOptions.cs
// Licensed to the .NET Foundation under one or more 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.Options; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class InternalDiagnosticsOptions { private const string LocalRegistryPath = @"Roslyn\Internal\Diagnostics\"; public static readonly Option2<bool> PreferLiveErrorsOnOpenedFiles = new(nameof(InternalDiagnosticsOptions), "Live errors will be preferred over errors from build on opened files from same analyzer", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Live errors will be preferred over errors from build on opened files from same analyzer")); public static readonly Option2<bool> PreferBuildErrorsOverLiveErrors = new(nameof(InternalDiagnosticsOptions), "Errors from build will be preferred over live errors from same analyzer", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Errors from build will be preferred over live errors from same analyzer")); public static readonly Option2<bool> PutCustomTypeInBingSearch = new(nameof(InternalDiagnosticsOptions), nameof(PutCustomTypeInBingSearch), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "PutCustomTypeInBingSearch")); public static readonly Option2<bool> CrashOnAnalyzerException = new(nameof(InternalDiagnosticsOptions), nameof(CrashOnAnalyzerException), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "CrashOnAnalyzerException")); public static readonly Option2<bool> ProcessHiddenDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(ProcessHiddenDiagnostics), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Process Hidden Diagnostics")); public static readonly Option2<DiagnosticMode> NormalDiagnosticMode = new(nameof(InternalDiagnosticsOptions), nameof(NormalDiagnosticMode), defaultValue: DiagnosticMode.Default, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "NormalDiagnosticMode")); public static readonly Option2<DiagnosticMode> RazorDiagnosticMode = new(nameof(InternalDiagnosticsOptions), nameof(RazorDiagnosticMode), defaultValue: DiagnosticMode.Pull, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "RazorDiagnosticMode")); public static readonly Option2<bool> EnableFileLoggingForDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(EnableFileLoggingForDiagnostics), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "EnableFileLoggingForDiagnostics")); } }
// Licensed to the .NET Foundation under one or more 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.Options; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class InternalDiagnosticsOptions { private const string LocalRegistryPath = @"Roslyn\Internal\Diagnostics\"; public static readonly Option2<bool> PreferLiveErrorsOnOpenedFiles = new(nameof(InternalDiagnosticsOptions), "Live errors will be preferred over errors from build on opened files from same analyzer", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Live errors will be preferred over errors from build on opened files from same analyzer")); public static readonly Option2<bool> PreferBuildErrorsOverLiveErrors = new(nameof(InternalDiagnosticsOptions), "Errors from build will be preferred over live errors from same analyzer", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Errors from build will be preferred over live errors from same analyzer")); public static readonly Option2<bool> PutCustomTypeInBingSearch = new(nameof(InternalDiagnosticsOptions), nameof(PutCustomTypeInBingSearch), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "PutCustomTypeInBingSearch")); public static readonly Option2<bool> CrashOnAnalyzerException = new(nameof(InternalDiagnosticsOptions), nameof(CrashOnAnalyzerException), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "CrashOnAnalyzerException")); public static readonly Option2<bool> ProcessHiddenDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(ProcessHiddenDiagnostics), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Process Hidden Diagnostics")); public static readonly Option2<DiagnosticMode> NormalDiagnosticMode = new(nameof(InternalDiagnosticsOptions), nameof(NormalDiagnosticMode), defaultValue: DiagnosticMode.Default, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "NormalDiagnosticMode")); public static readonly Option2<DiagnosticMode> RazorDiagnosticMode = new(nameof(InternalDiagnosticsOptions), nameof(RazorDiagnosticMode), defaultValue: DiagnosticMode.Pull, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "RazorDiagnosticMode")); public static readonly Option2<bool> EnableFileLoggingForDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(EnableFileLoggingForDiagnostics), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "EnableFileLoggingForDiagnostics")); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IMethodBodyOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.IOperation)] public class IOperationTests_IMethodBodyOperation : SemanticModelTestBase { [Fact] public void RegularMethodBody_01() { // No block or expression body string source = @" abstract class C { public abstract void M(); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_02() { // Block body with throw string source = @" class C { public void M() { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public void ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_03() { // Expression body with throw string source = @" class C { public void M() => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public void ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_04() { // Block and expression body with throw string source = @" class C { public void M() { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M() { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'public void ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, 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, IsInvalid) (Syntax: 'null') .erroneous body {R1} { Block[B2] - Block [UnReachable] Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, 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, IsInvalid) (Syntax: 'null') } Block[B3] - Exit [UnReachable] Predecessors (0) Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_05() { // Block body with non-exceptional flow string source = @" class C { public void M(int i, int j) { j = i; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = i') Left: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_06() { // Expression body with non-exceptional flow string source = @" class C { public void M(int i, int j) => j = i; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = i') Left: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_07() { // Block and expression body with non-exceptional flow string source = @" class C { public void M(int i1, int i2, int j1, int j2) { i1 = j1; } => i2 = j2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M(int i, int j) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M(int i1, int i2, int j1, int j2) { i1 = j1; } => i2 = j2;").WithLocation(4, 5)); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i1 = j1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i1 = j1') Left: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i1') Right: IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j1') Next (Regular) Block[B3] .erroneous body {R1} { Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'i2 = j2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i2 = j2') Left: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i2') Right: IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_08() { // Verify block body with a return statement, followed by throw in expression body. // This caught an assert when attempting to link current basic block which was already linked to exit. string source = @" class C { public void M() { return; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M() { return; } => throw null;").WithLocation(4, 5)); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] .erroneous body {R1} { Block[B1] - Block [UnReachable] Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, 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, IsInvalid) (Syntax: 'null') } Block[B2] - Exit Predecessors: [B0] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_09() { // Expression body with local declarations. string source = @" class C { public void M() => M2(out int x); void M2(out int x) => x = 0; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().First(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'M2(out int x)') Expression: IInvocationOperation ( void C.M2(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(out int x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') 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] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_10() { // Block body and expression body with local declarations. string source = @" class C { public void M() { } => M2(out int x); void M2(out int x) => x = 0; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M() { } => M2(out int x);").WithLocation(4, 5)); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().First(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] .erroneous body {R1} { Locals: [System.Int32 x] Block[B1] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2(out int x)') Expression: IInvocationOperation ( void C.M2(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2(out int x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') 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] Leaving: {R1} } Block[B2] - Exit Predecessors: [B0] [B1] Statements (0) "); } [Fact] public void OperatorBody_01() { string source = @" abstract class C { public static C operator ! (C x); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,30): error CS0501: 'C.operator !(C)' must declare a body because it is not marked abstract, extern, or partial // public static C operator ! (C x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "!").WithArguments("C.operator !(C)").WithLocation(4, 30) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void OperatorMethodBody_02() { string source = @" class C { public static C operator ! (C x) { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void OperatorMethodBody_03() { string source = @" class C { public static C operator ! (C x) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void OperatorMethodBody_04() { string source = @" class C { public static C operator ! (C x) { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public static C operator ! (C x) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public static C operator ! (C x) { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'public stat ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsInvalid, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void ConversionBody_01() { string source = @" abstract class C { public static implicit operator int(C x); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,37): error CS0501: 'C.implicit operator int(C)' must declare a body because it is not marked abstract, extern, or partial // public static implicit operator int(C x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("C.implicit operator int(C)").WithLocation(4, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void ConversionMethodBody_02() { string source = @" class C { public static implicit operator int(C x) { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void ConversionMethodBody_03() { string source = @" class C { public static implicit operator int(C x) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void ConversionMethodBody_04() { string source = @" class C { public static implicit operator int(C x) { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public static implicit operator int(C x) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public static implicit operator int(C x) { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'public stat ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void DestructorBody_01() { string source = @" abstract class C { ~C(); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,6): error CS0501: 'C.~C()' must declare a body because it is not marked abstract, extern, or partial // ~C(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.~C()").WithLocation(4, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void DestructorBody_02() { string source = @" class C { ~C() { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: '~C() ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void DestructorBody_03() { string source = @" class C { ~C() => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: '~C() ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void DestructorBody_04() { string source = @" class C { ~C() { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // ~C() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"~C() { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: '~C() ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void AccessorBody_01() { string source = @" abstract class C { abstract protected int P { get; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void AccessorBody_02() { string source = @" class C { int P { set { throw null; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'set ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void AccessorBody_03() { string source = @" class C { event System.Action E { add => throw null; remove {throw null;} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().First(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'add => throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void AccessorBody_04() { string source = @" class C { event System.Action E { remove { throw null; } => throw null; add { throw null;} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,9): error CS8057: Block bodies and expression bodies cannot both be provided. // remove Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"remove { throw null; } => throw null;").WithLocation(6, 9) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().First(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'remove ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void AccessorBody_05() { string source = @" abstract class C { int P { get; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int P { get; } => throw null; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int P { get; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.IOperation)] public class IOperationTests_IMethodBodyOperation : SemanticModelTestBase { [Fact] public void RegularMethodBody_01() { // No block or expression body string source = @" abstract class C { public abstract void M(); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_02() { // Block body with throw string source = @" class C { public void M() { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public void ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_03() { // Expression body with throw string source = @" class C { public void M() => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public void ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_04() { // Block and expression body with throw string source = @" class C { public void M() { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M() { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'public void ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, 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, IsInvalid) (Syntax: 'null') .erroneous body {R1} { Block[B2] - Block [UnReachable] Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, 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, IsInvalid) (Syntax: 'null') } Block[B3] - Exit [UnReachable] Predecessors (0) Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_05() { // Block body with non-exceptional flow string source = @" class C { public void M(int i, int j) { j = i; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = i') Left: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_06() { // Expression body with non-exceptional flow string source = @" class C { public void M(int i, int j) => j = i; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = i') Left: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_07() { // Block and expression body with non-exceptional flow string source = @" class C { public void M(int i1, int i2, int j1, int j2) { i1 = j1; } => i2 = j2; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M(int i, int j) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M(int i1, int i2, int j1, int j2) { i1 = j1; } => i2 = j2;").WithLocation(4, 5)); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i1 = j1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i1 = j1') Left: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i1') Right: IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j1') Next (Regular) Block[B3] .erroneous body {R1} { Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'i2 = j2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i2 = j2') Left: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i2') Right: IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_08() { // Verify block body with a return statement, followed by throw in expression body. // This caught an assert when attempting to link current basic block which was already linked to exit. string source = @" class C { public void M() { return; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M() { return; } => throw null;").WithLocation(4, 5)); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] .erroneous body {R1} { Block[B1] - Block [UnReachable] Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, 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, IsInvalid) (Syntax: 'null') } Block[B2] - Exit Predecessors: [B0] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_09() { // Expression body with local declarations. string source = @" class C { public void M() => M2(out int x); void M2(out int x) => x = 0; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().First(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'M2(out int x)') Expression: IInvocationOperation ( void C.M2(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(out int x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') 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] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [CompilerTrait(CompilerFeature.Dataflow)] [Fact] public void RegularMethodBody_10() { // Block body and expression body with local declarations. string source = @" class C { public void M() { } => M2(out int x); void M2(out int x) => x = 0; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public void M() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public void M() { } => M2(out int x);").WithLocation(4, 5)); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().First(); VerifyFlowGraph(compilation, node1, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] .erroneous body {R1} { Locals: [System.Int32 x] Block[B1] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2(out int x)') Expression: IInvocationOperation ( void C.M2(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2(out int x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') 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] Leaving: {R1} } Block[B2] - Exit Predecessors: [B0] [B1] Statements (0) "); } [Fact] public void OperatorBody_01() { string source = @" abstract class C { public static C operator ! (C x); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,30): error CS0501: 'C.operator !(C)' must declare a body because it is not marked abstract, extern, or partial // public static C operator ! (C x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "!").WithArguments("C.operator !(C)").WithLocation(4, 30) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void OperatorMethodBody_02() { string source = @" class C { public static C operator ! (C x) { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void OperatorMethodBody_03() { string source = @" class C { public static C operator ! (C x) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void OperatorMethodBody_04() { string source = @" class C { public static C operator ! (C x) { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public static C operator ! (C x) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public static C operator ! (C x) { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'public stat ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsInvalid, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void ConversionBody_01() { string source = @" abstract class C { public static implicit operator int(C x); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,37): error CS0501: 'C.implicit operator int(C)' must declare a body because it is not marked abstract, extern, or partial // public static implicit operator int(C x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("C.implicit operator int(C)").WithLocation(4, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void ConversionMethodBody_02() { string source = @" class C { public static implicit operator int(C x) { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void ConversionMethodBody_03() { string source = @" class C { public static implicit operator int(C x) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'public stat ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void ConversionMethodBody_04() { string source = @" class C { public static implicit operator int(C x) { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public static implicit operator int(C x) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public static implicit operator int(C x) { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'public stat ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'throw null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void DestructorBody_01() { string source = @" abstract class C { ~C(); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,6): error CS0501: 'C.~C()' must declare a body because it is not marked abstract, extern, or partial // ~C(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.~C()").WithLocation(4, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void DestructorBody_02() { string source = @" class C { ~C() { throw null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: '~C() ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void DestructorBody_03() { string source = @" class C { ~C() => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: '~C() ... throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void DestructorBody_04() { string source = @" class C { ~C() { throw null; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // ~C() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"~C() { throw null; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<BaseMethodDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: '~C() ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void AccessorBody_01() { string source = @" abstract class C { abstract protected int P { get; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } [Fact] public void AccessorBody_02() { string source = @" class C { int P { set { throw null; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'set ... row null; }') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') ExpressionBody: null "); } [Fact] public void AccessorBody_03() { string source = @" class C { event System.Action E { add => throw null; remove {throw null;} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().First(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'add => throw null;') BlockBody: null ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, 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') "); } [Fact] public void AccessorBody_04() { string source = @" class C { event System.Action E { remove { throw null; } => throw null; add { throw null;} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,9): error CS8057: Block bodies and expression bodies cannot both be provided. // remove Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"remove { throw null; } => throw null;").WithLocation(6, 9) ); var tree = compilation.SyntaxTrees.Single(); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().First(); compilation.VerifyOperationTree(node1, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'remove ... throw null;') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }') IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ExpressionBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null') Expression: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "); } [Fact] public void AccessorBody_05() { string source = @" abstract class C { int P { get; } => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // int P { get; } => throw null; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "int P { get; } => throw null;").WithLocation(4, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Null(model.GetOperation(node1)); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/KeywordHighlighting/ConditionalPreprocessorHighlighterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class ConditionalPreprocessorHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(ConditionalPreprocessorHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { {|Cursor:[|#if|]|} Debug CheckConsistency(); #if Trace WriteToLog(this.ToString()); #else Exit(); #endif [|#endif|] CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { [|#if|] Debug CheckConsistency(); #if Trace WriteToLog(this.ToString()); #else Exit(); #endif {|Cursor:[|#endif|]|} CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_1() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { #if Debug CheckConsistency(); {|Cursor:[|#if|]|} Trace WriteToLog(this.ToString()); [|#else|] Exit(); [|#endif|] #endif CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_2() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { #if Debug CheckConsistency(); [|#if|] Trace WriteToLog(this.ToString()); {|Cursor:[|#else|]|} Exit(); [|#endif|] #endif CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_3() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { #if Debug CheckConsistency(); [|#if|] Trace WriteToLog(this.ToString()); [|#else|] Exit(); {|Cursor:[|#endif|]|} #endif CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_1() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 {|Cursor:[|#if|]|} Goo1 [|#elif|] Goo2 [|#else|] [|#endif|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_2() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 [|#if|] Goo1 {|Cursor:[|#elif|]|} Goo2 [|#else|] [|#endif|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_3() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 [|#if|] Goo1 [|#elif|] Goo2 {|Cursor:[|#else|]|} [|#endif|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_4() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 [|#if|] Goo1 [|#elif|] Goo2 [|#else|] {|Cursor:[|#endif|]|} } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class ConditionalPreprocessorHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(ConditionalPreprocessorHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { {|Cursor:[|#if|]|} Debug CheckConsistency(); #if Trace WriteToLog(this.ToString()); #else Exit(); #endif [|#endif|] CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { [|#if|] Debug CheckConsistency(); #if Trace WriteToLog(this.ToString()); #else Exit(); #endif {|Cursor:[|#endif|]|} CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_1() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { #if Debug CheckConsistency(); {|Cursor:[|#if|]|} Trace WriteToLog(this.ToString()); [|#else|] Exit(); [|#endif|] #endif CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_2() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { #if Debug CheckConsistency(); [|#if|] Trace WriteToLog(this.ToString()); {|Cursor:[|#else|]|} Exit(); [|#endif|] #endif CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_3() { await TestAsync( @"class C { void M() { #define Debug #undef Trace class PurchaseTransaction { void Commit() { #if Debug CheckConsistency(); [|#if|] Trace WriteToLog(this.ToString()); [|#else|] Exit(); {|Cursor:[|#endif|]|} #endif CommitHelper(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_1() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 {|Cursor:[|#if|]|} Goo1 [|#elif|] Goo2 [|#else|] [|#endif|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_2() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 [|#if|] Goo1 {|Cursor:[|#elif|]|} Goo2 [|#else|] [|#endif|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_3() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 [|#if|] Goo1 [|#elif|] Goo2 {|Cursor:[|#else|]|} [|#endif|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample4_4() { await TestAsync( @"class C { void M() { #define Goo1 #define Goo2 [|#if|] Goo1 [|#elif|] Goo2 [|#else|] {|Cursor:[|#endif|]|} } }"); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpOrderModifiersDiagnosticAnalyzer : AbstractOrderModifiersDiagnosticAnalyzer { public CSharpOrderModifiersDiagnosticAnalyzer() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance, LanguageNames.CSharp) { } protected override void Recurse( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode root) { foreach (var child in root.ChildNodesAndTokens()) { if (child.IsNode) { var node = child.AsNode(); if (node is MemberDeclarationSyntax memberDeclaration) { CheckModifiers(context, preferredOrder, severity, memberDeclaration); // Recurse and check children. Note: we only do this if we're on an actual // member declaration. Once we hit something that isn't, we don't need to // keep recursing. This prevents us from actually entering things like method // bodies. Recurse(context, preferredOrder, severity, node); } else if (node is AccessorListSyntax accessorList) { foreach (var accessor in accessorList.Accessors) { CheckModifiers(context, preferredOrder, severity, accessor); } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpOrderModifiersDiagnosticAnalyzer : AbstractOrderModifiersDiagnosticAnalyzer { public CSharpOrderModifiersDiagnosticAnalyzer() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance, LanguageNames.CSharp) { } protected override void Recurse( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode root) { foreach (var child in root.ChildNodesAndTokens()) { if (child.IsNode) { var node = child.AsNode(); if (node is MemberDeclarationSyntax memberDeclaration) { CheckModifiers(context, preferredOrder, severity, memberDeclaration); // Recurse and check children. Note: we only do this if we're on an actual // member declaration. Once we hit something that isn't, we don't need to // keep recursing. This prevents us from actually entering things like method // bodies. Recurse(context, preferredOrder, severity, node); } else if (node is AccessorListSyntax accessorList) { foreach (var accessor in accessorList.Accessors) { CheckModifiers(context, preferredOrder, severity, accessor); } } } } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/CodeAnalysisTest/Collections/ArrayBuilderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class ArrayBuilderTests { [Fact] public void RemoveDuplicates1() { var builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; builder.RemoveDuplicates(); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, builder); builder = new ArrayBuilder<int> { 1 }; builder.RemoveDuplicates(); AssertEx.Equal(new[] { 1 }, builder); builder = new ArrayBuilder<int>(); builder.RemoveDuplicates(); AssertEx.Equal(new int[0], builder); } [Fact] public void SortAndRemoveDuplicates1() { var builder = new ArrayBuilder<int> { 5, 1, 3, 2, 4, 1, 2 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, builder); builder = new ArrayBuilder<int> { 1 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1 }, builder); builder = new ArrayBuilder<int> { 1, 2 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2 }, builder); builder = new ArrayBuilder<int> { 1, 2, 3 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2, 3 }, builder); builder = new ArrayBuilder<int> { 1, 2, 2 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2 }, builder); builder = new ArrayBuilder<int>(); builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new int[0], builder); } [Fact] public void SelectDistinct1() { var builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, builder.SelectDistinct(n => n)); builder = new ArrayBuilder<int> { 1 }; AssertEx.Equal(new[] { 1 }, builder.SelectDistinct(n => n)); builder = new ArrayBuilder<int>(); AssertEx.Equal(new int[0], builder.SelectDistinct(n => n)); builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; AssertEx.Equal(new[] { 10 }, builder.SelectDistinct(n => 10)); builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; AssertEx.Equal(new byte[] { 1, 2, 3, 4, 5 }, builder.SelectDistinct(n => (byte)n)); } [Fact] public void AddRange() { var builder = new ArrayBuilder<int>(); builder.AddRange(new int[0], 0, 0); AssertEx.Equal(new int[0], builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 0, 3); AssertEx.Equal(new[] { 1, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 2, 0); AssertEx.Equal(new[] { 1, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 1, 1); AssertEx.Equal(new[] { 1, 2, 3, 2 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 1, 2); AssertEx.Equal(new[] { 1, 2, 3, 2, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 2, 1); AssertEx.Equal(new[] { 1, 2, 3, 2, 2, 3, 3 }, builder.ToArray()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class ArrayBuilderTests { [Fact] public void RemoveDuplicates1() { var builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; builder.RemoveDuplicates(); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, builder); builder = new ArrayBuilder<int> { 1 }; builder.RemoveDuplicates(); AssertEx.Equal(new[] { 1 }, builder); builder = new ArrayBuilder<int>(); builder.RemoveDuplicates(); AssertEx.Equal(new int[0], builder); } [Fact] public void SortAndRemoveDuplicates1() { var builder = new ArrayBuilder<int> { 5, 1, 3, 2, 4, 1, 2 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, builder); builder = new ArrayBuilder<int> { 1 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1 }, builder); builder = new ArrayBuilder<int> { 1, 2 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2 }, builder); builder = new ArrayBuilder<int> { 1, 2, 3 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2, 3 }, builder); builder = new ArrayBuilder<int> { 1, 2, 2 }; builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new[] { 1, 2 }, builder); builder = new ArrayBuilder<int>(); builder.SortAndRemoveDuplicates(Comparer<int>.Default); AssertEx.Equal(new int[0], builder); } [Fact] public void SelectDistinct1() { var builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, builder.SelectDistinct(n => n)); builder = new ArrayBuilder<int> { 1 }; AssertEx.Equal(new[] { 1 }, builder.SelectDistinct(n => n)); builder = new ArrayBuilder<int>(); AssertEx.Equal(new int[0], builder.SelectDistinct(n => n)); builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; AssertEx.Equal(new[] { 10 }, builder.SelectDistinct(n => 10)); builder = new ArrayBuilder<int> { 1, 2, 3, 2, 4, 5, 1 }; AssertEx.Equal(new byte[] { 1, 2, 3, 4, 5 }, builder.SelectDistinct(n => (byte)n)); } [Fact] public void AddRange() { var builder = new ArrayBuilder<int>(); builder.AddRange(new int[0], 0, 0); AssertEx.Equal(new int[0], builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 0, 3); AssertEx.Equal(new[] { 1, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 2, 0); AssertEx.Equal(new[] { 1, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 1, 1); AssertEx.Equal(new[] { 1, 2, 3, 2 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 1, 2); AssertEx.Equal(new[] { 1, 2, 3, 2, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 2, 1); AssertEx.Equal(new[] { 1, 2, 3, 2, 2, 3, 3 }, builder.ToArray()); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Wrapping/AbstractWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Wrapping { using Microsoft.CodeAnalysis.Indentation; /// <summary> /// Common implementation of all <see cref="ISyntaxWrapper"/>. This type takes care of a lot of common logic for /// all of them, including: /// /// 1. Keeping track of code action invocations, allowing code actions to then be prioritized on /// subsequent invocations. /// /// 2. Checking nodes and tokens to make sure they are safe to be wrapped. /// /// Individual subclasses may be targeted at specific syntactic forms. For example, wrapping /// lists, or wrapping logical expressions. /// </summary> internal abstract partial class AbstractSyntaxWrapper : ISyntaxWrapper { protected IIndentationService IndentationService { get; } protected AbstractSyntaxWrapper(IIndentationService indentationService) => IndentationService = indentationService; public abstract Task<ICodeActionComputer> TryCreateComputerAsync(Document document, int position, SyntaxNode node, CancellationToken cancellationToken); protected static async Task<bool> ContainsUnformattableContentAsync( Document document, IEnumerable<SyntaxNodeOrToken> nodesAndTokens, CancellationToken cancellationToken) { // For now, don't offer if any item spans multiple lines. We'll very likely screw up // formatting badly. If this is really important to support, we can put in the effort // to properly move multi-line items around (which would involve properly fixing up the // indentation of lines within them. // // https://github.com/dotnet/roslyn/issues/31575 var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); foreach (var item in nodesAndTokens) { if (item == null || item.Span.IsEmpty) { return true; } var firstToken = item.IsToken ? item.AsToken() : item.AsNode().GetFirstToken(); var lastToken = item.IsToken ? item.AsToken() : item.AsNode().GetLastToken(); // Note: we check if things are on the same line, even in the case of a single token. // This is so that we don't try to wrap multiline tokens either (like a multi-line // string). if (!sourceText.AreOnSameLine(firstToken, lastToken)) { 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. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Wrapping { using Microsoft.CodeAnalysis.Indentation; /// <summary> /// Common implementation of all <see cref="ISyntaxWrapper"/>. This type takes care of a lot of common logic for /// all of them, including: /// /// 1. Keeping track of code action invocations, allowing code actions to then be prioritized on /// subsequent invocations. /// /// 2. Checking nodes and tokens to make sure they are safe to be wrapped. /// /// Individual subclasses may be targeted at specific syntactic forms. For example, wrapping /// lists, or wrapping logical expressions. /// </summary> internal abstract partial class AbstractSyntaxWrapper : ISyntaxWrapper { protected IIndentationService IndentationService { get; } protected AbstractSyntaxWrapper(IIndentationService indentationService) => IndentationService = indentationService; public abstract Task<ICodeActionComputer> TryCreateComputerAsync(Document document, int position, SyntaxNode node, CancellationToken cancellationToken); protected static async Task<bool> ContainsUnformattableContentAsync( Document document, IEnumerable<SyntaxNodeOrToken> nodesAndTokens, CancellationToken cancellationToken) { // For now, don't offer if any item spans multiple lines. We'll very likely screw up // formatting badly. If this is really important to support, we can put in the effort // to properly move multi-line items around (which would involve properly fixing up the // indentation of lines within them. // // https://github.com/dotnet/roslyn/issues/31575 var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); foreach (var item in nodesAndTokens) { if (item == null || item.Span.IsEmpty) { return true; } var firstToken = item.IsToken ? item.AsToken() : item.AsNode().GetFirstToken(); var lastToken = item.IsToken ? item.AsToken() : item.AsNode().GetLastToken(); // Note: we check if things are on the same line, even in the case of a single token. // This is so that we don't try to wrap multiline tokens either (like a multi-line // string). if (!sourceText.AreOnSameLine(firstToken, lastToken)) { return true; } } return false; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Options/LanguageSettingsPersisterProvider.cs
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.TextManager.Interop; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class LanguageSettingsPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private LanguageSettingsPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LanguageSettingsPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { if (_lazyPersister is not null) { return _lazyPersister; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var textManager = (IVsTextManager4?)await _serviceProvider.GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true); Assumes.Present(textManager); _lazyPersister ??= new LanguageSettingsPersister(_threadingContext, textManager, _optionService); return _lazyPersister; } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.TextManager.Interop; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class LanguageSettingsPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private LanguageSettingsPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LanguageSettingsPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { if (_lazyPersister is not null) { return _lazyPersister; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var textManager = (IVsTextManager4?)await _serviceProvider.GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true); Assumes.Present(textManager); _lazyPersister ??= new LanguageSettingsPersister(_threadingContext, textManager, _optionService); return _lazyPersister; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Test/CodeModel/FileCodeImportTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeImportTests : AbstractFileCodeElementTests { public FileCodeImportTests() : base(@"using System; using Goo = System.Data;") { } private CodeImport GetCodeImport(object path) { return (CodeImport)GetCodeElement(path); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Name() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.Name; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void FullName() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.FullName; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Kind() { var import = GetCodeImport(1); Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Namespace() { var import = GetCodeImport(1); Assert.Equal("System", import.Namespace); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Alias() { var import = GetCodeImport(2); Assert.Equal("Goo", import.Alias); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Navigate() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, startPoint.Line); Assert.Equal(13, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_WholeWithAttributes() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Navigate() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, endPoint.Line); Assert.Equal(24, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_WholeWithAttributes() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void StartPoint() { var import = GetCodeImport(2); var startPoint = import.StartPoint; Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void EndPoint() { var import = GetCodeImport(2); var endPoint = import.EndPoint; Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeImportTests : AbstractFileCodeElementTests { public FileCodeImportTests() : base(@"using System; using Goo = System.Data;") { } private CodeImport GetCodeImport(object path) { return (CodeImport)GetCodeElement(path); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Name() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.Name; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void FullName() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.FullName; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Kind() { var import = GetCodeImport(1); Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Namespace() { var import = GetCodeImport(1); Assert.Equal("System", import.Namespace); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Alias() { var import = GetCodeImport(2); Assert.Equal("Goo", import.Alias); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Navigate() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, startPoint.Line); Assert.Equal(13, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_WholeWithAttributes() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Navigate() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, endPoint.Line); Assert.Equal(24, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_WholeWithAttributes() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void StartPoint() { var import = GetCodeImport(2); var startPoint = import.StartPoint; Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void EndPoint() { var import = GetCodeImport(2); var endPoint = import.EndPoint; Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Dependencies/PooledObjects/PooledDelegates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.PooledObjects { /// <summary> /// Provides pooled delegate instances to help avoid closure allocations for delegates that require a state argument /// with APIs that do not provide appropriate overloads with state arguments. /// </summary> internal static class PooledDelegates { private static class DefaultDelegatePool<T> where T : class, new() { public static readonly ObjectPool<T> Instance = new(() => new T(), 20); } private static Releaser GetPooledDelegate<TPooled, TArg, TUnboundDelegate, TBoundDelegate>(TUnboundDelegate unboundDelegate, TArg argument, out TBoundDelegate boundDelegate) where TPooled : AbstractDelegateWithBoundArgument<TPooled, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { var obj = DefaultDelegatePool<TPooled>.Instance.Allocate(); obj.Initialize(unboundDelegate, argument); boundDelegate = obj.BoundDelegate; return new Releaser(obj); } /// <summary> /// Gets an <see cref="Action"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(() => this.DoSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction(arg => arg.self.DoSomething(arg.x), (self: this, x), out Action action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<TArg>(Action<TArg> unboundAction, TArg argument, out Action boundAction) => GetPooledDelegate<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(a => this.DoSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, arg) => arg.self.DoSomething(a, arg.x), (self: this, x), out Action&lt;int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, TArg>(Action<T1, TArg> unboundAction, TArg argument, out Action<T1> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b) => this.DoSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, arg) => arg.self.DoSomething(a, b, arg.x), (self: this, x), out Action&lt;int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, TArg>(Action<T1, T2, TArg> unboundAction, TArg argument, out Action<T1, T2> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2, T3}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b, c) => this.DoSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, c, arg) => arg.self.DoSomething(a, b, c, arg.x), (self: this, x), out Action&lt;int, int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, T3, TArg>(Action<T1, T2, T3, TArg> unboundAction, TArg argument, out Action<T1, T2, T3> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>>(unboundAction, argument, out boundAction); /// <summary> /// Gets a <see cref="Func{TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(() => this.IsSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction(arg => arg.self.IsSomething(arg.x), (self: this, x), out Func&lt;bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<TArg, TResult>(Func<TArg, TResult> unboundFunction, TArg argument, out Func<TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(a => this.IsSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, arg) => arg.self.IsSomething(a, arg.x), (self: this, x), out Func&lt;int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, TArg, TResult>(Func<T1, TArg, TResult> unboundFunction, TArg argument, out Func<T1, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b) => this.IsSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, arg) => arg.self.IsSomething(a, b, arg.x), (self: this, x), out Func&lt;int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, TArg, TResult>(Func<T1, T2, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, T3, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b, c) => this.IsSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, c, arg) => arg.self.IsSomething(a, b, c, arg.x), (self: this, x), out Func&lt;int, int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, T3, TArg, TResult>(Func<T1, T2, T3, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, T3, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// A releaser for a pooled delegate. /// </summary> /// <remarks> /// <para>This type is intended for use as the resource of a <c>using</c> statement. When used in this manner, /// <see cref="Dispose"/> should not be called explicitly.</para> /// /// <para>If used without a <c>using</c> statement, calling <see cref="Dispose"/> is optional. If the call is /// omitted, the object will not be returned to the pool. The behavior of this type if <see cref="Dispose"/> is /// called multiple times is undefined.</para> /// </remarks> [NonCopyable] public struct Releaser : IDisposable { private readonly Poolable _pooledObject; internal Releaser(Poolable pooledObject) { _pooledObject = pooledObject; } public void Dispose() => _pooledObject.ClearAndFree(); } internal abstract class Poolable { public abstract void ClearAndFree(); } private abstract class AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate> : Poolable where TSelf : AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { protected AbstractDelegateWithBoundArgument() { BoundDelegate = Bind(); UnboundDelegate = null!; Argument = default!; } public TBoundDelegate BoundDelegate { get; } public TUnboundDelegate UnboundDelegate { get; private set; } public TArg Argument { get; private set; } public void Initialize(TUnboundDelegate unboundDelegate, TArg argument) { UnboundDelegate = unboundDelegate; Argument = argument; } public sealed override void ClearAndFree() { Argument = default!; UnboundDelegate = null!; DefaultDelegatePool<TSelf>.Instance.Free((TSelf)this); } protected abstract TBoundDelegate Bind(); } private sealed class ActionWithBoundArgument<TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action> { protected override Action Bind() => () => UnboundDelegate(Argument); } private sealed class ActionWithBoundArgument<T1, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>> { protected override Action<T1> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class ActionWithBoundArgument<T1, T2, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>> { protected override Action<T1, T2> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class ActionWithBoundArgument<T1, T2, T3, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>> { protected override Action<T1, T2, T3> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } private sealed class FuncWithBoundArgument<TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>> { protected override Func<TResult> Bind() => () => UnboundDelegate(Argument); } private sealed class FuncWithBoundArgument<T1, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>> { protected override Func<T1, TResult> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class FuncWithBoundArgument<T1, T2, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>> { protected override Func<T1, T2, TResult> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class FuncWithBoundArgument<T1, T2, T3, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>> { protected override Func<T1, T2, T3, TResult> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } [AttributeUsage(AttributeTargets.Struct)] private sealed class NonCopyableAttribute : Attribute { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.PooledObjects { /// <summary> /// Provides pooled delegate instances to help avoid closure allocations for delegates that require a state argument /// with APIs that do not provide appropriate overloads with state arguments. /// </summary> internal static class PooledDelegates { private static class DefaultDelegatePool<T> where T : class, new() { public static readonly ObjectPool<T> Instance = new(() => new T(), 20); } private static Releaser GetPooledDelegate<TPooled, TArg, TUnboundDelegate, TBoundDelegate>(TUnboundDelegate unboundDelegate, TArg argument, out TBoundDelegate boundDelegate) where TPooled : AbstractDelegateWithBoundArgument<TPooled, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { var obj = DefaultDelegatePool<TPooled>.Instance.Allocate(); obj.Initialize(unboundDelegate, argument); boundDelegate = obj.BoundDelegate; return new Releaser(obj); } /// <summary> /// Gets an <see cref="Action"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(() => this.DoSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction(arg => arg.self.DoSomething(arg.x), (self: this, x), out Action action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<TArg>(Action<TArg> unboundAction, TArg argument, out Action boundAction) => GetPooledDelegate<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(a => this.DoSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, arg) => arg.self.DoSomething(a, arg.x), (self: this, x), out Action&lt;int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, TArg>(Action<T1, TArg> unboundAction, TArg argument, out Action<T1> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b) => this.DoSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, arg) => arg.self.DoSomething(a, b, arg.x), (self: this, x), out Action&lt;int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, TArg>(Action<T1, T2, TArg> unboundAction, TArg argument, out Action<T1, T2> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2, T3}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b, c) => this.DoSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, c, arg) => arg.self.DoSomething(a, b, c, arg.x), (self: this, x), out Action&lt;int, int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, T3, TArg>(Action<T1, T2, T3, TArg> unboundAction, TArg argument, out Action<T1, T2, T3> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>>(unboundAction, argument, out boundAction); /// <summary> /// Gets a <see cref="Func{TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(() => this.IsSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction(arg => arg.self.IsSomething(arg.x), (self: this, x), out Func&lt;bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<TArg, TResult>(Func<TArg, TResult> unboundFunction, TArg argument, out Func<TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(a => this.IsSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, arg) => arg.self.IsSomething(a, arg.x), (self: this, x), out Func&lt;int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, TArg, TResult>(Func<T1, TArg, TResult> unboundFunction, TArg argument, out Func<T1, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b) => this.IsSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, arg) => arg.self.IsSomething(a, b, arg.x), (self: this, x), out Func&lt;int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, TArg, TResult>(Func<T1, T2, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, T3, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b, c) => this.IsSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, c, arg) => arg.self.IsSomething(a, b, c, arg.x), (self: this, x), out Func&lt;int, int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, T3, TArg, TResult>(Func<T1, T2, T3, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, T3, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// A releaser for a pooled delegate. /// </summary> /// <remarks> /// <para>This type is intended for use as the resource of a <c>using</c> statement. When used in this manner, /// <see cref="Dispose"/> should not be called explicitly.</para> /// /// <para>If used without a <c>using</c> statement, calling <see cref="Dispose"/> is optional. If the call is /// omitted, the object will not be returned to the pool. The behavior of this type if <see cref="Dispose"/> is /// called multiple times is undefined.</para> /// </remarks> [NonCopyable] public struct Releaser : IDisposable { private readonly Poolable _pooledObject; internal Releaser(Poolable pooledObject) { _pooledObject = pooledObject; } public void Dispose() => _pooledObject.ClearAndFree(); } internal abstract class Poolable { public abstract void ClearAndFree(); } private abstract class AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate> : Poolable where TSelf : AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { protected AbstractDelegateWithBoundArgument() { BoundDelegate = Bind(); UnboundDelegate = null!; Argument = default!; } public TBoundDelegate BoundDelegate { get; } public TUnboundDelegate UnboundDelegate { get; private set; } public TArg Argument { get; private set; } public void Initialize(TUnboundDelegate unboundDelegate, TArg argument) { UnboundDelegate = unboundDelegate; Argument = argument; } public sealed override void ClearAndFree() { Argument = default!; UnboundDelegate = null!; DefaultDelegatePool<TSelf>.Instance.Free((TSelf)this); } protected abstract TBoundDelegate Bind(); } private sealed class ActionWithBoundArgument<TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action> { protected override Action Bind() => () => UnboundDelegate(Argument); } private sealed class ActionWithBoundArgument<T1, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>> { protected override Action<T1> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class ActionWithBoundArgument<T1, T2, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>> { protected override Action<T1, T2> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class ActionWithBoundArgument<T1, T2, T3, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>> { protected override Action<T1, T2, T3> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } private sealed class FuncWithBoundArgument<TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>> { protected override Func<TResult> Bind() => () => UnboundDelegate(Argument); } private sealed class FuncWithBoundArgument<T1, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>> { protected override Func<T1, TResult> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class FuncWithBoundArgument<T1, T2, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>> { protected override Func<T1, T2, TResult> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class FuncWithBoundArgument<T1, T2, T3, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>> { protected override Func<T1, T2, T3, TResult> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } [AttributeUsage(AttributeTargets.Struct)] private sealed class NonCopyableAttribute : Attribute { } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateMember/GenerateVariable/IGenerateVariableService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable { internal interface IGenerateVariableService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateVariableAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable { internal interface IGenerateVariableService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateVariableAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/EditAndContinue/MockEditAndContinueWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal delegate void ActionOut<T>(out T arg); internal class MockEditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl; public Func<Solution, ActiveStatementSpanProvider, ManagedInstructionId, LinePositionSpan?>? GetCurrentActiveStatementPositionImpl; public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl; public Func<Solution, IManagedEditAndContinueDebuggerService, ImmutableArray<DocumentId>, bool, bool, DebuggingSessionId>? StartDebuggingSessionImpl; public ActionOut<ImmutableArray<DocumentId>>? EndDebuggingSessionImpl; public Func<Solution, ActiveStatementSpanProvider, string?, bool>? HasChangesImpl; public Func<Solution, ActiveStatementSpanProvider, EmitSolutionUpdateResults>? EmitSolutionUpdateImpl; public Func<Solution, ManagedInstructionId, bool?>? IsActiveStatementInExceptionRegionImpl; public Action<Document>? OnSourceFileUpdatedImpl; public ActionOut<ImmutableArray<DocumentId>>? CommitSolutionUpdateImpl; public ActionOut<ImmutableArray<DocumentId>>? BreakStateEnteredImpl; public Action? DiscardSolutionUpdateImpl; public Func<Document, ActiveStatementSpanProvider, ImmutableArray<Diagnostic>>? GetDocumentDiagnosticsImpl; public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; BreakStateEnteredImpl?.Invoke(out documentsToReanalyze); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; CommitSolutionUpdateImpl?.Invoke(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; EndDebuggingSessionImpl?.Invoke(out documentsToReanalyze); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((GetCurrentActiveStatementPositionImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, instructionId)); public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) => new((HasChangesImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, sourceFilePath)); public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((IsActiveStatementInExceptionRegionImpl ?? throw new NotImplementedException()).Invoke(solution, instructionId)); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) => new((StartDebuggingSessionImpl ?? throw new NotImplementedException()).Invoke(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal delegate void ActionOut<T>(out T arg); internal class MockEditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl; public Func<Solution, ActiveStatementSpanProvider, ManagedInstructionId, LinePositionSpan?>? GetCurrentActiveStatementPositionImpl; public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl; public Func<Solution, IManagedEditAndContinueDebuggerService, ImmutableArray<DocumentId>, bool, bool, DebuggingSessionId>? StartDebuggingSessionImpl; public ActionOut<ImmutableArray<DocumentId>>? EndDebuggingSessionImpl; public Func<Solution, ActiveStatementSpanProvider, string?, bool>? HasChangesImpl; public Func<Solution, ActiveStatementSpanProvider, EmitSolutionUpdateResults>? EmitSolutionUpdateImpl; public Func<Solution, ManagedInstructionId, bool?>? IsActiveStatementInExceptionRegionImpl; public Action<Document>? OnSourceFileUpdatedImpl; public ActionOut<ImmutableArray<DocumentId>>? CommitSolutionUpdateImpl; public ActionOut<ImmutableArray<DocumentId>>? BreakStateEnteredImpl; public Action? DiscardSolutionUpdateImpl; public Func<Document, ActiveStatementSpanProvider, ImmutableArray<Diagnostic>>? GetDocumentDiagnosticsImpl; public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; BreakStateEnteredImpl?.Invoke(out documentsToReanalyze); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; CommitSolutionUpdateImpl?.Invoke(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; EndDebuggingSessionImpl?.Invoke(out documentsToReanalyze); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((GetCurrentActiveStatementPositionImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, instructionId)); public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) => new((HasChangesImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, sourceFilePath)); public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((IsActiveStatementInExceptionRegionImpl ?? throw new NotImplementedException()).Invoke(solution, instructionId)); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) => new((StartDebuggingSessionImpl ?? throw new NotImplementedException()).Invoke(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics)); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker_Patterns.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullableWalker { /// <summary> /// Learn something about the input from a test of a given expression against a given pattern. The given /// state is updated to note that any slots that are tested against `null` may be null. /// </summary> private void LearnFromAnyNullPatterns( BoundExpression expression, BoundPattern pattern) { int slot = MakeSlot(expression); LearnFromAnyNullPatterns(slot, expression.Type, pattern); } private void VisitPatternForRewriting(BoundPattern pattern) { // Don't let anything under the pattern actually affect current state, // as we're only visiting for nullable information. Debug.Assert(!IsConditionalState); var currentState = State; VisitWithoutDiagnostics(pattern); SetState(currentState); } public override BoundNode VisitPositionalSubpattern(BoundPositionalSubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitPropertySubpattern(BoundPropertySubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitRecursivePattern(BoundRecursivePattern node) { Visit(node.DeclaredType); VisitAndUnsplitAll(node.Deconstruction); VisitAndUnsplitAll(node.Properties); Visit(node.VariableAccess); return null; } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node) { Visit(node.VariableAccess); Visit(node.DeclaredType); return null; } public override BoundNode VisitDiscardPattern(BoundDiscardPattern node) { return null; } public override BoundNode VisitTypePattern(BoundTypePattern node) { Visit(node.DeclaredType); return null; } public override BoundNode VisitRelationalPattern(BoundRelationalPattern node) { Visit(node.Value); return null; } public override BoundNode VisitNegatedPattern(BoundNegatedPattern node) { Visit(node.Negated); return null; } public override BoundNode VisitBinaryPattern(BoundBinaryPattern node) { Visit(node.Left); Visit(node.Right); return null; } public override BoundNode VisitITuplePattern(BoundITuplePattern node) { VisitAndUnsplitAll(node.Subpatterns); return null; } /// <summary> /// Learn from any constant null patterns appearing in the pattern. /// </summary> /// <param name="inputType">Type type of the input expression (before nullable analysis). /// Used to determine which types can contain null.</param> private void LearnFromAnyNullPatterns( int inputSlot, TypeSymbol inputType, BoundPattern pattern) { if (inputSlot <= 0) return; // https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we // can get information for any nodes in the pattern. VisitPatternForRewriting(pattern); switch (pattern) { case BoundConstantPattern cp: bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null; if (isExplicitNullCheck) { // Since we're not branching on this null test here, we just infer the top level // nullability. We'll branch on it later. LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundDeclarationPattern _: case BoundDiscardPattern _: case BoundITuplePattern _: case BoundRelationalPattern _: break; // nothing to learn case BoundTypePattern tp: if (tp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundRecursivePattern rp: { if (rp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } // for positional part: we only learn from tuples (not Deconstruct) if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault) { var elements = inputType.TupleElements; for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++) { BoundSubpattern item = rp.Deconstruction[i]; FieldSymbol element = elements[i]; LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern); } } // for property part if (!rp.Properties.IsDefault) { foreach (BoundPropertySubpattern subpattern in rp.Properties) { if (subpattern.Member is BoundPropertySubpatternMember member) { LearnFromAnyNullPatterns(getExtendedPropertySlot(member, inputSlot), member.Type, subpattern.Pattern); } } } } break; case BoundNegatedPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated); break; case BoundBinaryPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Left); LearnFromAnyNullPatterns(inputSlot, inputType, p.Right); break; default: throw ExceptionUtilities.UnexpectedValue(pattern); } int getExtendedPropertySlot(BoundPropertySubpatternMember member, int inputSlot) { if (member.Symbol is null) { return -1; } if (member.Receiver is not null) { inputSlot = getExtendedPropertySlot(member.Receiver, inputSlot); } if (inputSlot < 0) { return inputSlot; } return GetOrCreateSlot(member.Symbol, inputSlot); } } protected override LocalState VisitSwitchStatementDispatch(BoundSwitchStatement node) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern); } } } // visit switch header Visit(node.Expression); var expressionState = ResultType; DeclareLocals(node.InnerLocals); foreach (var section in node.SwitchSections) { // locals can be alive across jumps in the switch sections, so we declare them early. DeclareLocals(section.Locals); } var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state: UnreachableState(), believedReachable: false); SetState(labelResult.state); PendingBranches.Add(new PendingBranch(label, this.State, label.Label)); } } var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState(); labelStateMap.Free(); return afterSwitchState; } protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) { TakeIncrementalSnapshot(node); SetState(UnreachableState()); foreach (var label in node.SwitchLabels) { TakeIncrementalSnapshot(label); VisitPatternForRewriting(label.Pattern); VisitLabel(label.Label, node); } VisitStatementList(node); } private struct PossiblyConditionalState { public LocalState State; public LocalState StateWhenTrue; public LocalState StateWhenFalse; public bool IsConditionalState; public PossiblyConditionalState(LocalState stateWhenTrue, LocalState stateWhenFalse) { StateWhenTrue = stateWhenTrue.Clone(); StateWhenFalse = stateWhenFalse.Clone(); IsConditionalState = true; State = default; } public PossiblyConditionalState(LocalState state) { StateWhenTrue = StateWhenFalse = default; IsConditionalState = false; State = state.Clone(); } public static PossiblyConditionalState Create(NullableWalker nullableWalker) { return nullableWalker.IsConditionalState ? new PossiblyConditionalState(nullableWalker.StateWhenTrue, nullableWalker.StateWhenFalse) : new PossiblyConditionalState(nullableWalker.State); } public PossiblyConditionalState Clone() { return IsConditionalState ? new PossiblyConditionalState(StateWhenTrue, StateWhenFalse) : new PossiblyConditionalState(State); } } private PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)> LearnFromDecisionDag( SyntaxNode node, BoundDecisionDag decisionDag, BoundExpression expression, TypeWithState expressionType, PossiblyConditionalState? stateWhenNotNullOpt) { // We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are // not copying the input to evaluate the patterns. In this way we infer non-nullability of the original // variable's parts based on matched pattern parts. Mutations in `when` clauses can show the inaccuracy // of analysis based on this choice. var rootTemp = BoundDagTemp.ForOriginalInput(expression); int originalInputSlot = MakeSlot(expression); if (originalInputSlot <= 0) { originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(compilation), rootTemp); } Debug.Assert(originalInputSlot > 0); // If the input of the switch (or is-pattern expression) is a tuple literal, we reuse the slots of // those expressions (when possible), pretending that we are not copying them into a temporary ValueTuple instance // to evaluate the patterns. In this way we infer non-nullability of the original element's parts. // We do not extend such courtesy to nested tuple literals. var originalInputElementSlots = expression is BoundTupleExpression tuple ? tuple.Arguments.SelectAsArray(static (a, w) => w.MakeSlot(a), this) : default; var originalInputMap = PooledDictionary<int, BoundExpression>.GetInstance(); originalInputMap.Add(originalInputSlot, expression); var tempMap = PooledDictionary<BoundDagTemp, (int slot, TypeSymbol type)>.GetInstance(); Debug.Assert(isDerivedType(NominalSlotType(originalInputSlot), expressionType.Type)); tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type)); var nodeStateMap = PooledDictionary<BoundDecisionDagNode, (PossiblyConditionalState state, bool believedReachable)>.GetInstance(); nodeStateMap.Add(decisionDag.RootNode, (state: PossiblyConditionalState.Create(this), believedReachable: true)); var labelStateMap = PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>.GetInstance(); foreach (var dagNode in decisionDag.TopologicallySortedNodes) { bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable); Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes (PossiblyConditionalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable; if (nodeState.IsConditionalState) { SetConditionalState(nodeState.StateWhenTrue, nodeState.StateWhenFalse); } else { SetState(nodeState.State); } switch (dagNode) { case BoundEvaluationDecisionDagNode p: { var evaluation = p.Evaluation; (int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable; Debug.Assert(inputSlot > 0); switch (evaluation) { case BoundDagDeconstructEvaluation e: { // https://github.com/dotnet/roslyn/issues/34232 // We may need to recompute the Deconstruct method for a deconstruction if // the receiver type has changed (e.g. its nested nullability). var method = e.DeconstructMethod; int extensionExtra = method.RequiresInstanceReceiver ? 0 : 1; for (int i = 0; i < method.ParameterCount - extensionExtra; i++) { var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, parameterType.Type, e, i); int outputSlot = makeDagTempSlot(parameterType, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, parameterType.Type); } break; } case BoundDagTypeEvaluation e: { var output = new BoundDagTemp(e.Syntax, e.Type, e); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; int outputSlot; switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedUseSiteInfo).Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: outputSlot = inputSlot; break; case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _): outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true); if (outputSlot < 0) goto default; break; default: outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output); break; } Debug.Assert(!IsConditionalState); Unsplit(); State[outputSlot] = NullableFlowState.NotNull; addToTempMap(output, outputSlot, e.Type); break; } case BoundDagFieldEvaluation e: { Debug.Assert(inputSlot > 0); var field = (FieldSymbol)AsMemberOfType(inputType, e.Field); var type = field.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = -1; var originalTupleElement = e.Input.IsOriginalInput && !originalInputElementSlots.IsDefault ? field : null; if (originalTupleElement is not null) { // Re-use the slot of the element/expression if possible outputSlot = originalInputElementSlots[originalTupleElement.TupleElementIndex]; } if (outputSlot <= 0) { outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true); if (originalTupleElement is not null && outputSlot > 0) { // The expression in the tuple could not be assigned a slot (for example, `a?.b`), // so we had to create a slot for the tuple element instead. // We'll remember that so that we can apply any learnings to the expression. if (!originalInputMap.ContainsKey(outputSlot)) { originalInputMap.Add(outputSlot, ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } else { Debug.Assert(originalInputMap[outputSlot] == ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } } } if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } case BoundDagPropertyEvaluation e: { Debug.Assert(inputSlot > 0); var property = (PropertySymbol)AsMemberOfType(inputType, e.Property); var type = property.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true); if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); if (property.GetMethod is not null) { // A property evaluation splits the state if MemberNotNullWhen is used ApplyMemberPostConditions(inputSlot, property.GetMethod); } break; } case BoundDagIndexEvaluation e: { var type = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated); var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = makeDagTempSlot(type, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } default: throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind); } gotoNodeWithCurrentState(p.Next, nodeBelievedReachable); break; } case BoundTestDecisionDagNode p: { var test = p.Test; bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType); Debug.Assert(foundTemp); (int inputSlot, TypeSymbol inputType) = slotAndType; Debug.Assert(test is not BoundDagNonNullTest || !IsConditionalState); Split(); switch (test) { case BoundDagTypeTest: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagNonNullTest t: var inputMaybeNull = this.StateWhenTrue[inputSlot].MayBeNull(); if (inputSlot > 0) { MarkDependentSlotsNotNull(inputSlot, inputType, ref this.StateWhenFalse); if (t.IsExplicitTest) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenFalse, markDependentSlotsNotNull: false); } learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputMaybeNull); break; case BoundDagExplicitNullTest _: if (inputSlot > 0) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue, markDependentSlotsNotNull: true); learnFromNonNullTest(inputSlot, ref this.StateWhenFalse); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagValueTest t: Debug.Assert(t.Value != ConstantValue.Null); // When we compare `bool?` inputs to bool constants, we follow a graph roughly like the following: // [0]: t0 != null ? [1] : [5] // [1]: t1 = (bool)t0; [2] // [2] (this node): t1 == boolConstant ? [3] : [4] // ...(remaining states) if (stateWhenNotNullOpt is { } stateWhenNotNull && t.Input.Source is BoundDagTypeEvaluation { Input: { IsOriginalInput: true } }) { SetPossiblyConditionalState(stateWhenNotNull); Split(); } else if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } bool isFalseTest = t.Value == ConstantValue.False; gotoNode(p.WhenTrue, isFalseTest ? this.StateWhenFalse : this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, isFalseTest ? this.StateWhenTrue : this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagRelationalTest _: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; default: throw ExceptionUtilities.UnexpectedValue(test.Kind); } break; } case BoundLeafDecisionDagNode d: // We have one leaf decision dag node per reachable label Unsplit(); // Could be split in pathological cases like `false switch { ... }` labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable)); break; case BoundWhenDecisionDagNode w: // bind the pattern variables, inferring their types as well Unsplit(); foreach (var binding in w.Bindings) { var variableAccess = binding.VariableAccess; var tempSource = binding.TempContainingValue; var foundTemp = tempMap.TryGetValue(tempSource, out var tempSlotAndType); if (foundTemp) // in erroneous programs, we might not have seen a temp defined. { var (tempSlot, tempType) = tempSlotAndType; var tempState = this.State[tempSlot]; if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol local } boundLocal) { var value = TypeWithState.Create(tempType, tempState); var inferredType = value.ToTypeWithAnnotations(compilation, asAnnotatedType: boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType); if (_variables.TryGetType(local, out var existingType)) { // merge inferred nullable annotation from different branches of the decision tree inferredType = TypeWithAnnotations.Create(inferredType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation)); } _variables.SetType(local, inferredType); int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true); if (localSlot > 0) { TrackNullableStateForAssignment(valueOpt: null, inferredType, localSlot, TypeWithState.Create(tempType, tempState), tempSlot); } } else { // https://github.com/dotnet/roslyn/issues/34144 perform inference for top-level var-declared fields in scripts } } } if (w.WhenExpression != null && w.WhenExpression.ConstantValue != ConstantValue.True) { VisitCondition(w.WhenExpression); Debug.Assert(this.IsConditionalState); gotoNode(w.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(w.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); } else { Debug.Assert(w.WhenFalse is null); gotoNode(w.WhenTrue, this.State, nodeBelievedReachable); } break; default: throw ExceptionUtilities.UnexpectedValue(dagNode.Kind); } } SetUnreachable(); // the decision dag is always complete (no fall-through) originalInputMap.Free(); tempMap.Free(); nodeStateMap.Free(); return labelStateMap; void learnFromNonNullTest(int inputSlot, ref LocalState state) { if (stateWhenNotNullOpt is { } stateWhenNotNull && inputSlot == originalInputSlot) { state = CloneAndUnsplit(ref stateWhenNotNull); } LearnFromNonNullTest(inputSlot, ref state); if (originalInputMap.TryGetValue(inputSlot, out var expression)) LearnFromNonNullTest(expression, ref state); } void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type) { // We need to track all dag temps, so there should be a slot Debug.Assert(slot > 0); if (tempMap.TryGetValue(output, out var outputSlotAndType)) { // The dag temp has already been allocated on another branch of the dag Debug.Assert(outputSlotAndType.slot == slot); Debug.Assert(isDerivedType(outputSlotAndType.type, type)); } else { Debug.Assert(NominalSlotType(slot) is var slotType && (slotType.IsErrorType() || isDerivedType(slotType, type))); tempMap.Add(output, (slot, type)); } } bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType) { if (derivedType.IsErrorType() || baseType.IsErrorType()) return true; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedUseSiteInfo).Kind switch { ConversionKind.Identity => true, ConversionKind.ImplicitReference => true, ConversionKind.Boxing => true, _ => false, }; } void gotoNodeWithCurrentState(BoundDecisionDagNode node, bool believedReachable) { if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { switch (IsConditionalState, stateAndReachable.state.IsConditionalState) { case (true, true): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (true, false): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.State); Join(ref this.StateWhenFalse, ref stateAndReachable.state.State); break; case (false, true): Debug.Assert(false); Split(); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (false, false): Join(ref this.State, ref stateAndReachable.state.State); break; } believedReachable |= stateAndReachable.believedReachable; } nodeStateMap[node] = (PossiblyConditionalState.Create(this), believedReachable); } void gotoNode(BoundDecisionDagNode node, LocalState state, bool believedReachable) { PossiblyConditionalState result; if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { result = stateAndReachable.state; switch (result.IsConditionalState) { case true: Debug.Assert(false); Join(ref result.StateWhenTrue, ref state); Join(ref result.StateWhenFalse, ref state); break; case false: Join(ref result.State, ref state); break; } believedReachable |= stateAndReachable.believedReachable; } else { result = new PossiblyConditionalState(state); } nodeStateMap[node] = (result, believedReachable); } int makeDagTempSlot(TypeWithAnnotations type, BoundDagTemp temp) { object slotKey = (node, temp); return GetOrCreatePlaceholderSlot(slotKey, type); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { bool inferType = !node.WasTargetTyped; VisitSwitchExpressionCore(node, inferType); return null; } public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) { // This method is only involved in method inference with unbound lambdas. VisitSwitchExpressionCore(node, inferType: true); return null; } private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var arm in node.SwitchArms) { LearnFromAnyNullPatterns(slot, originalInputType, arm.Pattern); } } Visit(node.Expression); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); var endState = UnreachableState(); if (!node.ReportedNotExhaustive && node.DefaultLabel != null && labelStateMap.TryGetValue(node.DefaultLabel, out var defaultLabelState) && defaultLabelState.believedReachable) { SetState(defaultLabelState.state); var nodes = node.DecisionDag.TopologicallySortedNodes; var leaf = nodes.Where(n => n is BoundLeafDecisionDagNode leaf && leaf.Label == node.DefaultLabel).First(); var samplePattern = PatternExplainer.SamplePatternForPathToDagNode( BoundDagTemp.ForOriginalInput(node.Expression), nodes, leaf, nullPaths: true, out bool requiresFalseWhenClause, out _); ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull; ReportDiagnostic( warningCode, ((SwitchExpressionSyntax)node.Syntax).SwitchKeyword.GetLocation(), samplePattern); } // collect expressions, conversions and result types int numSwitchArms = node.SwitchArms.Length; var conversions = ArrayBuilder<Conversion>.GetInstance(numSwitchArms); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(numSwitchArms); var expressions = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); foreach (var arm in node.SwitchArms) { SetState(getStateForArm(arm)); // https://github.com/dotnet/roslyn/issues/35836 Is this where we want to take the snapshot? TakeIncrementalSnapshot(arm); VisitPatternForRewriting(arm.Pattern); (BoundExpression expression, Conversion conversion) = RemoveConversion(arm.Value, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(arm.Value, expression); expressions.Add(expression); conversions.Add(conversion); var armType = VisitRvalueWithState(expression); resultTypes.Add(armType); Join(ref endState, ref this.State); // Build placeholders for inference in order to preserve annotations. placeholderBuilder.Add(CreatePlaceholderIfNecessary(expression, armType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeSymbol inferredType = (inferType ? BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo) : null) ?? node.Type?.SetUnknownNullabilityForReferenceTypes(); var inferredTypeWithAnnotations = TypeWithAnnotations.Create(inferredType); NullableFlowState inferredState; if (inferType) { if (inferredType is null) { // This can happen when we're inferring the return type of a lambda, or when there are no arms (an error case). // For this case, we don't need to do any work, as the unconverted switch expression can't contribute info, and // there is nothing that is being publicly exposed to the semantic model. Debug.Assert((node is BoundUnconvertedSwitchExpression && _returnTypesOpt is not null) || node is BoundSwitchExpression { SwitchArms: { Length: 0 } }); inferredState = default; } else { for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var arm = node.SwitchArms[i]; var armState = getStateForArm(arm); resultTypes[i] = ConvertConditionalOperandOrSwitchExpressionArmResult(arm.Value, nodeForSyntax, conversions[i], inferredTypeWithAnnotations, resultTypes[i], armState, armState.Reachable); } inferredState = BestTypeInferrer.GetNullableState(resultTypes); } } else { var states = ArrayBuilder<(LocalState, TypeWithState, bool)>.GetInstance(numSwitchArms); for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var armState = getStateForArm(node.SwitchArms[i]); states.Add((armState, resultTypes[i], armState.Reachable)); } ConditionalInfoForConversion.Add(node, states.ToImmutableAndFree()); inferredState = BestTypeInferrer.GetNullableState(resultTypes); } var resultType = TypeWithState.Create(inferredType, inferredState); conversions.Free(); resultTypes.Free(); expressions.Free(); labelStateMap.Free(); SetState(endState); SetResult(node, resultType, inferredTypeWithAnnotations); LocalState getStateForArm(BoundSwitchExpressionArm arm) => !arm.Pattern.HasErrors && labelStateMap.TryGetValue(arm.Label, out var labelState) ? labelState.state : UnreachableState(); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); LearnFromAnyNullPatterns(node.Expression, node.Pattern); VisitPatternForRewriting(node.Pattern); var hasStateWhenNotNull = VisitPossibleConditionalAccess(node.Expression, out var conditionalStateWhenNotNull); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, hasStateWhenNotNull ? conditionalStateWhenNotNull : null); var trueState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out var s1) ? s1.state : UnreachableState(); var falseState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out var s2) ? s2.state : UnreachableState(); labelStateMap.Free(); SetConditionalState(trueState, falseState); SetNotNullResult(node); 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullableWalker { /// <summary> /// Learn something about the input from a test of a given expression against a given pattern. The given /// state is updated to note that any slots that are tested against `null` may be null. /// </summary> private void LearnFromAnyNullPatterns( BoundExpression expression, BoundPattern pattern) { int slot = MakeSlot(expression); LearnFromAnyNullPatterns(slot, expression.Type, pattern); } private void VisitPatternForRewriting(BoundPattern pattern) { // Don't let anything under the pattern actually affect current state, // as we're only visiting for nullable information. Debug.Assert(!IsConditionalState); var currentState = State; VisitWithoutDiagnostics(pattern); SetState(currentState); } public override BoundNode VisitPositionalSubpattern(BoundPositionalSubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitPropertySubpattern(BoundPropertySubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitRecursivePattern(BoundRecursivePattern node) { Visit(node.DeclaredType); VisitAndUnsplitAll(node.Deconstruction); VisitAndUnsplitAll(node.Properties); Visit(node.VariableAccess); return null; } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node) { Visit(node.VariableAccess); Visit(node.DeclaredType); return null; } public override BoundNode VisitDiscardPattern(BoundDiscardPattern node) { return null; } public override BoundNode VisitTypePattern(BoundTypePattern node) { Visit(node.DeclaredType); return null; } public override BoundNode VisitRelationalPattern(BoundRelationalPattern node) { Visit(node.Value); return null; } public override BoundNode VisitNegatedPattern(BoundNegatedPattern node) { Visit(node.Negated); return null; } public override BoundNode VisitBinaryPattern(BoundBinaryPattern node) { Visit(node.Left); Visit(node.Right); return null; } public override BoundNode VisitITuplePattern(BoundITuplePattern node) { VisitAndUnsplitAll(node.Subpatterns); return null; } /// <summary> /// Learn from any constant null patterns appearing in the pattern. /// </summary> /// <param name="inputType">Type type of the input expression (before nullable analysis). /// Used to determine which types can contain null.</param> private void LearnFromAnyNullPatterns( int inputSlot, TypeSymbol inputType, BoundPattern pattern) { if (inputSlot <= 0) return; // https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we // can get information for any nodes in the pattern. VisitPatternForRewriting(pattern); switch (pattern) { case BoundConstantPattern cp: bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null; if (isExplicitNullCheck) { // Since we're not branching on this null test here, we just infer the top level // nullability. We'll branch on it later. LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundDeclarationPattern _: case BoundDiscardPattern _: case BoundITuplePattern _: case BoundRelationalPattern _: break; // nothing to learn case BoundTypePattern tp: if (tp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundRecursivePattern rp: { if (rp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } // for positional part: we only learn from tuples (not Deconstruct) if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault) { var elements = inputType.TupleElements; for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++) { BoundSubpattern item = rp.Deconstruction[i]; FieldSymbol element = elements[i]; LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern); } } // for property part if (!rp.Properties.IsDefault) { foreach (BoundPropertySubpattern subpattern in rp.Properties) { if (subpattern.Member is BoundPropertySubpatternMember member) { LearnFromAnyNullPatterns(getExtendedPropertySlot(member, inputSlot), member.Type, subpattern.Pattern); } } } } break; case BoundNegatedPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated); break; case BoundBinaryPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Left); LearnFromAnyNullPatterns(inputSlot, inputType, p.Right); break; default: throw ExceptionUtilities.UnexpectedValue(pattern); } int getExtendedPropertySlot(BoundPropertySubpatternMember member, int inputSlot) { if (member.Symbol is null) { return -1; } if (member.Receiver is not null) { inputSlot = getExtendedPropertySlot(member.Receiver, inputSlot); } if (inputSlot < 0) { return inputSlot; } return GetOrCreateSlot(member.Symbol, inputSlot); } } protected override LocalState VisitSwitchStatementDispatch(BoundSwitchStatement node) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern); } } } // visit switch header Visit(node.Expression); var expressionState = ResultType; DeclareLocals(node.InnerLocals); foreach (var section in node.SwitchSections) { // locals can be alive across jumps in the switch sections, so we declare them early. DeclareLocals(section.Locals); } var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state: UnreachableState(), believedReachable: false); SetState(labelResult.state); PendingBranches.Add(new PendingBranch(label, this.State, label.Label)); } } var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState(); labelStateMap.Free(); return afterSwitchState; } protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) { TakeIncrementalSnapshot(node); SetState(UnreachableState()); foreach (var label in node.SwitchLabels) { TakeIncrementalSnapshot(label); VisitPatternForRewriting(label.Pattern); VisitLabel(label.Label, node); } VisitStatementList(node); } private struct PossiblyConditionalState { public LocalState State; public LocalState StateWhenTrue; public LocalState StateWhenFalse; public bool IsConditionalState; public PossiblyConditionalState(LocalState stateWhenTrue, LocalState stateWhenFalse) { StateWhenTrue = stateWhenTrue.Clone(); StateWhenFalse = stateWhenFalse.Clone(); IsConditionalState = true; State = default; } public PossiblyConditionalState(LocalState state) { StateWhenTrue = StateWhenFalse = default; IsConditionalState = false; State = state.Clone(); } public static PossiblyConditionalState Create(NullableWalker nullableWalker) { return nullableWalker.IsConditionalState ? new PossiblyConditionalState(nullableWalker.StateWhenTrue, nullableWalker.StateWhenFalse) : new PossiblyConditionalState(nullableWalker.State); } public PossiblyConditionalState Clone() { return IsConditionalState ? new PossiblyConditionalState(StateWhenTrue, StateWhenFalse) : new PossiblyConditionalState(State); } } private PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)> LearnFromDecisionDag( SyntaxNode node, BoundDecisionDag decisionDag, BoundExpression expression, TypeWithState expressionType, PossiblyConditionalState? stateWhenNotNullOpt) { // We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are // not copying the input to evaluate the patterns. In this way we infer non-nullability of the original // variable's parts based on matched pattern parts. Mutations in `when` clauses can show the inaccuracy // of analysis based on this choice. var rootTemp = BoundDagTemp.ForOriginalInput(expression); int originalInputSlot = MakeSlot(expression); if (originalInputSlot <= 0) { originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(compilation), rootTemp); } Debug.Assert(originalInputSlot > 0); // If the input of the switch (or is-pattern expression) is a tuple literal, we reuse the slots of // those expressions (when possible), pretending that we are not copying them into a temporary ValueTuple instance // to evaluate the patterns. In this way we infer non-nullability of the original element's parts. // We do not extend such courtesy to nested tuple literals. var originalInputElementSlots = expression is BoundTupleExpression tuple ? tuple.Arguments.SelectAsArray(static (a, w) => w.MakeSlot(a), this) : default; var originalInputMap = PooledDictionary<int, BoundExpression>.GetInstance(); originalInputMap.Add(originalInputSlot, expression); var tempMap = PooledDictionary<BoundDagTemp, (int slot, TypeSymbol type)>.GetInstance(); Debug.Assert(isDerivedType(NominalSlotType(originalInputSlot), expressionType.Type)); tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type)); var nodeStateMap = PooledDictionary<BoundDecisionDagNode, (PossiblyConditionalState state, bool believedReachable)>.GetInstance(); nodeStateMap.Add(decisionDag.RootNode, (state: PossiblyConditionalState.Create(this), believedReachable: true)); var labelStateMap = PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>.GetInstance(); foreach (var dagNode in decisionDag.TopologicallySortedNodes) { bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable); Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes (PossiblyConditionalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable; if (nodeState.IsConditionalState) { SetConditionalState(nodeState.StateWhenTrue, nodeState.StateWhenFalse); } else { SetState(nodeState.State); } switch (dagNode) { case BoundEvaluationDecisionDagNode p: { var evaluation = p.Evaluation; (int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable; Debug.Assert(inputSlot > 0); switch (evaluation) { case BoundDagDeconstructEvaluation e: { // https://github.com/dotnet/roslyn/issues/34232 // We may need to recompute the Deconstruct method for a deconstruction if // the receiver type has changed (e.g. its nested nullability). var method = e.DeconstructMethod; int extensionExtra = method.RequiresInstanceReceiver ? 0 : 1; for (int i = 0; i < method.ParameterCount - extensionExtra; i++) { var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, parameterType.Type, e, i); int outputSlot = makeDagTempSlot(parameterType, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, parameterType.Type); } break; } case BoundDagTypeEvaluation e: { var output = new BoundDagTemp(e.Syntax, e.Type, e); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; int outputSlot; switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedUseSiteInfo).Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: outputSlot = inputSlot; break; case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _): outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true); if (outputSlot < 0) goto default; break; default: outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output); break; } Debug.Assert(!IsConditionalState); Unsplit(); State[outputSlot] = NullableFlowState.NotNull; addToTempMap(output, outputSlot, e.Type); break; } case BoundDagFieldEvaluation e: { Debug.Assert(inputSlot > 0); var field = (FieldSymbol)AsMemberOfType(inputType, e.Field); var type = field.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = -1; var originalTupleElement = e.Input.IsOriginalInput && !originalInputElementSlots.IsDefault ? field : null; if (originalTupleElement is not null) { // Re-use the slot of the element/expression if possible outputSlot = originalInputElementSlots[originalTupleElement.TupleElementIndex]; } if (outputSlot <= 0) { outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true); if (originalTupleElement is not null && outputSlot > 0) { // The expression in the tuple could not be assigned a slot (for example, `a?.b`), // so we had to create a slot for the tuple element instead. // We'll remember that so that we can apply any learnings to the expression. if (!originalInputMap.ContainsKey(outputSlot)) { originalInputMap.Add(outputSlot, ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } else { Debug.Assert(originalInputMap[outputSlot] == ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } } } if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } case BoundDagPropertyEvaluation e: { Debug.Assert(inputSlot > 0); var property = (PropertySymbol)AsMemberOfType(inputType, e.Property); var type = property.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true); if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); if (property.GetMethod is not null) { // A property evaluation splits the state if MemberNotNullWhen is used ApplyMemberPostConditions(inputSlot, property.GetMethod); } break; } case BoundDagIndexEvaluation e: { var type = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated); var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = makeDagTempSlot(type, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } default: throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind); } gotoNodeWithCurrentState(p.Next, nodeBelievedReachable); break; } case BoundTestDecisionDagNode p: { var test = p.Test; bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType); Debug.Assert(foundTemp); (int inputSlot, TypeSymbol inputType) = slotAndType; Debug.Assert(test is not BoundDagNonNullTest || !IsConditionalState); Split(); switch (test) { case BoundDagTypeTest: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagNonNullTest t: var inputMaybeNull = this.StateWhenTrue[inputSlot].MayBeNull(); if (inputSlot > 0) { MarkDependentSlotsNotNull(inputSlot, inputType, ref this.StateWhenFalse); if (t.IsExplicitTest) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenFalse, markDependentSlotsNotNull: false); } learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputMaybeNull); break; case BoundDagExplicitNullTest _: if (inputSlot > 0) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue, markDependentSlotsNotNull: true); learnFromNonNullTest(inputSlot, ref this.StateWhenFalse); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagValueTest t: Debug.Assert(t.Value != ConstantValue.Null); // When we compare `bool?` inputs to bool constants, we follow a graph roughly like the following: // [0]: t0 != null ? [1] : [5] // [1]: t1 = (bool)t0; [2] // [2] (this node): t1 == boolConstant ? [3] : [4] // ...(remaining states) if (stateWhenNotNullOpt is { } stateWhenNotNull && t.Input.Source is BoundDagTypeEvaluation { Input: { IsOriginalInput: true } }) { SetPossiblyConditionalState(stateWhenNotNull); Split(); } else if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } bool isFalseTest = t.Value == ConstantValue.False; gotoNode(p.WhenTrue, isFalseTest ? this.StateWhenFalse : this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, isFalseTest ? this.StateWhenTrue : this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagRelationalTest _: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; default: throw ExceptionUtilities.UnexpectedValue(test.Kind); } break; } case BoundLeafDecisionDagNode d: // We have one leaf decision dag node per reachable label Unsplit(); // Could be split in pathological cases like `false switch { ... }` labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable)); break; case BoundWhenDecisionDagNode w: // bind the pattern variables, inferring their types as well Unsplit(); foreach (var binding in w.Bindings) { var variableAccess = binding.VariableAccess; var tempSource = binding.TempContainingValue; var foundTemp = tempMap.TryGetValue(tempSource, out var tempSlotAndType); if (foundTemp) // in erroneous programs, we might not have seen a temp defined. { var (tempSlot, tempType) = tempSlotAndType; var tempState = this.State[tempSlot]; if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol local } boundLocal) { var value = TypeWithState.Create(tempType, tempState); var inferredType = value.ToTypeWithAnnotations(compilation, asAnnotatedType: boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType); if (_variables.TryGetType(local, out var existingType)) { // merge inferred nullable annotation from different branches of the decision tree inferredType = TypeWithAnnotations.Create(inferredType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation)); } _variables.SetType(local, inferredType); int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true); if (localSlot > 0) { TrackNullableStateForAssignment(valueOpt: null, inferredType, localSlot, TypeWithState.Create(tempType, tempState), tempSlot); } } else { // https://github.com/dotnet/roslyn/issues/34144 perform inference for top-level var-declared fields in scripts } } } if (w.WhenExpression != null && w.WhenExpression.ConstantValue != ConstantValue.True) { VisitCondition(w.WhenExpression); Debug.Assert(this.IsConditionalState); gotoNode(w.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(w.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); } else { Debug.Assert(w.WhenFalse is null); gotoNode(w.WhenTrue, this.State, nodeBelievedReachable); } break; default: throw ExceptionUtilities.UnexpectedValue(dagNode.Kind); } } SetUnreachable(); // the decision dag is always complete (no fall-through) originalInputMap.Free(); tempMap.Free(); nodeStateMap.Free(); return labelStateMap; void learnFromNonNullTest(int inputSlot, ref LocalState state) { if (stateWhenNotNullOpt is { } stateWhenNotNull && inputSlot == originalInputSlot) { state = CloneAndUnsplit(ref stateWhenNotNull); } LearnFromNonNullTest(inputSlot, ref state); if (originalInputMap.TryGetValue(inputSlot, out var expression)) LearnFromNonNullTest(expression, ref state); } void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type) { // We need to track all dag temps, so there should be a slot Debug.Assert(slot > 0); if (tempMap.TryGetValue(output, out var outputSlotAndType)) { // The dag temp has already been allocated on another branch of the dag Debug.Assert(outputSlotAndType.slot == slot); Debug.Assert(isDerivedType(outputSlotAndType.type, type)); } else { Debug.Assert(NominalSlotType(slot) is var slotType && (slotType.IsErrorType() || isDerivedType(slotType, type))); tempMap.Add(output, (slot, type)); } } bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType) { if (derivedType.IsErrorType() || baseType.IsErrorType()) return true; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedUseSiteInfo).Kind switch { ConversionKind.Identity => true, ConversionKind.ImplicitReference => true, ConversionKind.Boxing => true, _ => false, }; } void gotoNodeWithCurrentState(BoundDecisionDagNode node, bool believedReachable) { if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { switch (IsConditionalState, stateAndReachable.state.IsConditionalState) { case (true, true): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (true, false): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.State); Join(ref this.StateWhenFalse, ref stateAndReachable.state.State); break; case (false, true): Debug.Assert(false); Split(); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (false, false): Join(ref this.State, ref stateAndReachable.state.State); break; } believedReachable |= stateAndReachable.believedReachable; } nodeStateMap[node] = (PossiblyConditionalState.Create(this), believedReachable); } void gotoNode(BoundDecisionDagNode node, LocalState state, bool believedReachable) { PossiblyConditionalState result; if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { result = stateAndReachable.state; switch (result.IsConditionalState) { case true: Debug.Assert(false); Join(ref result.StateWhenTrue, ref state); Join(ref result.StateWhenFalse, ref state); break; case false: Join(ref result.State, ref state); break; } believedReachable |= stateAndReachable.believedReachable; } else { result = new PossiblyConditionalState(state); } nodeStateMap[node] = (result, believedReachable); } int makeDagTempSlot(TypeWithAnnotations type, BoundDagTemp temp) { object slotKey = (node, temp); return GetOrCreatePlaceholderSlot(slotKey, type); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { bool inferType = !node.WasTargetTyped; VisitSwitchExpressionCore(node, inferType); return null; } public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) { // This method is only involved in method inference with unbound lambdas. VisitSwitchExpressionCore(node, inferType: true); return null; } private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var arm in node.SwitchArms) { LearnFromAnyNullPatterns(slot, originalInputType, arm.Pattern); } } Visit(node.Expression); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); var endState = UnreachableState(); if (!node.ReportedNotExhaustive && node.DefaultLabel != null && labelStateMap.TryGetValue(node.DefaultLabel, out var defaultLabelState) && defaultLabelState.believedReachable) { SetState(defaultLabelState.state); var nodes = node.DecisionDag.TopologicallySortedNodes; var leaf = nodes.Where(n => n is BoundLeafDecisionDagNode leaf && leaf.Label == node.DefaultLabel).First(); var samplePattern = PatternExplainer.SamplePatternForPathToDagNode( BoundDagTemp.ForOriginalInput(node.Expression), nodes, leaf, nullPaths: true, out bool requiresFalseWhenClause, out _); ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull; ReportDiagnostic( warningCode, ((SwitchExpressionSyntax)node.Syntax).SwitchKeyword.GetLocation(), samplePattern); } // collect expressions, conversions and result types int numSwitchArms = node.SwitchArms.Length; var conversions = ArrayBuilder<Conversion>.GetInstance(numSwitchArms); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(numSwitchArms); var expressions = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); foreach (var arm in node.SwitchArms) { SetState(getStateForArm(arm)); // https://github.com/dotnet/roslyn/issues/35836 Is this where we want to take the snapshot? TakeIncrementalSnapshot(arm); VisitPatternForRewriting(arm.Pattern); (BoundExpression expression, Conversion conversion) = RemoveConversion(arm.Value, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(arm.Value, expression); expressions.Add(expression); conversions.Add(conversion); var armType = VisitRvalueWithState(expression); resultTypes.Add(armType); Join(ref endState, ref this.State); // Build placeholders for inference in order to preserve annotations. placeholderBuilder.Add(CreatePlaceholderIfNecessary(expression, armType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeSymbol inferredType = (inferType ? BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo) : null) ?? node.Type?.SetUnknownNullabilityForReferenceTypes(); var inferredTypeWithAnnotations = TypeWithAnnotations.Create(inferredType); NullableFlowState inferredState; if (inferType) { if (inferredType is null) { // This can happen when we're inferring the return type of a lambda, or when there are no arms (an error case). // For this case, we don't need to do any work, as the unconverted switch expression can't contribute info, and // there is nothing that is being publicly exposed to the semantic model. Debug.Assert((node is BoundUnconvertedSwitchExpression && _returnTypesOpt is not null) || node is BoundSwitchExpression { SwitchArms: { Length: 0 } }); inferredState = default; } else { for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var arm = node.SwitchArms[i]; var armState = getStateForArm(arm); resultTypes[i] = ConvertConditionalOperandOrSwitchExpressionArmResult(arm.Value, nodeForSyntax, conversions[i], inferredTypeWithAnnotations, resultTypes[i], armState, armState.Reachable); } inferredState = BestTypeInferrer.GetNullableState(resultTypes); } } else { var states = ArrayBuilder<(LocalState, TypeWithState, bool)>.GetInstance(numSwitchArms); for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var armState = getStateForArm(node.SwitchArms[i]); states.Add((armState, resultTypes[i], armState.Reachable)); } ConditionalInfoForConversion.Add(node, states.ToImmutableAndFree()); inferredState = BestTypeInferrer.GetNullableState(resultTypes); } var resultType = TypeWithState.Create(inferredType, inferredState); conversions.Free(); resultTypes.Free(); expressions.Free(); labelStateMap.Free(); SetState(endState); SetResult(node, resultType, inferredTypeWithAnnotations); LocalState getStateForArm(BoundSwitchExpressionArm arm) => !arm.Pattern.HasErrors && labelStateMap.TryGetValue(arm.Label, out var labelState) ? labelState.state : UnreachableState(); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); LearnFromAnyNullPatterns(node.Expression, node.Pattern); VisitPatternForRewriting(node.Pattern); var hasStateWhenNotNull = VisitPossibleConditionalAccess(node.Expression, out var conditionalStateWhenNotNull); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, hasStateWhenNotNull ? conditionalStateWhenNotNull : null); var trueState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out var s1) ? s1.state : UnreachableState(); var falseState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out var s2) ? s2.state : UnreachableState(); labelStateMap.Free(); SetConditionalState(trueState, falseState); SetNotNullResult(node); return null; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/ISettingsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal interface ISettingsProvider<TData> { void RegisterViewModel(ISettingsEditorViewModel model); ImmutableArray<TData> GetCurrentDataSnapshot(); Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal interface ISettingsProvider<TData> { void RegisterViewModel(ISettingsEditorViewModel model); ImmutableArray<TData> GetCurrentDataSnapshot(); Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ReturnKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ReturnKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ReturnKeywordRecommender() : base(SyntaxKind.ReturnKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.TargetToken.IsAfterYieldKeyword() || IsAttributeContext(context, cancellationToken); } private static bool IsAttributeContext(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, cancellationToken) || (context.SyntaxTree.IsScript() && context.IsTypeAttributeContext(cancellationToken)) || context.IsStatementAttributeContext(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ReturnKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ReturnKeywordRecommender() : base(SyntaxKind.ReturnKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.TargetToken.IsAfterYieldKeyword() || IsAttributeContext(context, cancellationToken); } private static bool IsAttributeContext(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, cancellationToken) || (context.SyntaxTree.IsScript() && context.IsTypeAttributeContext(cancellationToken)) || context.IsStatementAttributeContext(); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.Analysis.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeStyle { // This part contains all the logic for hooking up the DiagnosticAnalyzer to the CodeStyleProvider. // All the code in this part is an implementation detail and is intentionally private so that // subclasses cannot change anything. All code relevant to subclasses relating to analysis // is contained in AbstractCodeStyleProvider.cs internal abstract partial class AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider> { public abstract class DiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public readonly TCodeStyleProvider _codeStyleProvider; protected DiagnosticAnalyzer(bool isUnnecessary = true, bool configurable = true) : this(new TCodeStyleProvider(), isUnnecessary, configurable) { } private DiagnosticAnalyzer(TCodeStyleProvider codeStyleProvider, bool isUnnecessary, bool configurable) : base(codeStyleProvider._descriptorId, codeStyleProvider._enforceOnBuild, codeStyleProvider._option, codeStyleProvider._language, codeStyleProvider._title, codeStyleProvider._message, isUnnecessary, configurable) { _codeStyleProvider = codeStyleProvider; } protected sealed override void InitializeWorker(Diagnostics.AnalysisContext context) => _codeStyleProvider.DiagnosticAnalyzerInitialize(new AnalysisContext(_codeStyleProvider, context)); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => _codeStyleProvider.GetAnalyzerCategory(); } /// <summary> /// Critically, we want to consolidate the logic about checking if the analyzer should run /// at all. i.e. if the user has their option set to 'none' or 'refactoring only' then we /// do not want the analyzer to run at all. /// /// To that end, we don't let the subclass have direct access to the real <see /// cref="Diagnostics.AnalysisContext"/>. Instead, we pass this type to the subclass for it /// register with. We then check if the registration should proceed given the <see /// cref="CodeStyleOption2{T}"/> /// and the current <see cref="SyntaxTree"/> being processed. If not, we don't do the /// actual registration. /// </summary> protected struct AnalysisContext { private readonly TCodeStyleProvider _codeStyleProvider; private readonly Diagnostics.AnalysisContext _context; public AnalysisContext(TCodeStyleProvider codeStyleProvider, Diagnostics.AnalysisContext context) { _codeStyleProvider = codeStyleProvider; _context = context; } public void RegisterCompilationStartAction(Action<Compilation, AnalysisContext> analyze) { var _this = this; _context.RegisterCompilationStartAction( c => analyze(c.Compilation, _this)); } public void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext, CodeStyleOption2<TOptionKind>> analyze) { var provider = _codeStyleProvider; _context.RegisterCodeBlockAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken)); } public void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext, CodeStyleOption2<TOptionKind>> analyze) { var provider = _codeStyleProvider; _context.RegisterSemanticModelAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken)); } public void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext, CodeStyleOption2<TOptionKind>> analyze) { var provider = _codeStyleProvider; _context.RegisterSyntaxTreeAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.Tree, c.CancellationToken)); } public void RegisterOperationAction( Action<OperationAnalysisContext, CodeStyleOption2<TOptionKind>> analyze, params OperationKind[] operationKinds) { var provider = _codeStyleProvider; _context.RegisterOperationAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.Operation.SemanticModel.SyntaxTree, c.CancellationToken), operationKinds); } public void RegisterSyntaxNodeAction<TSyntaxKind>( Action<SyntaxNodeAnalysisContext, CodeStyleOption2<TOptionKind>> analyze, params TSyntaxKind[] syntaxKinds) where TSyntaxKind : struct { var provider = _codeStyleProvider; _context.RegisterSyntaxNodeAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken), syntaxKinds); } private static void AnalyzeIfEnabled<TContext>( TCodeStyleProvider provider, TContext context, Action<TContext, CodeStyleOption2<TOptionKind>> analyze, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionValue = options.GetOption(provider._option, syntaxTree, cancellationToken); var severity = GetOptionSeverity(optionValue); switch (severity) { case ReportDiagnostic.Error: case ReportDiagnostic.Warn: case ReportDiagnostic.Info: break; default: // don't analyze if it's any other value. return; } analyze(context, optionValue); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeStyle { // This part contains all the logic for hooking up the DiagnosticAnalyzer to the CodeStyleProvider. // All the code in this part is an implementation detail and is intentionally private so that // subclasses cannot change anything. All code relevant to subclasses relating to analysis // is contained in AbstractCodeStyleProvider.cs internal abstract partial class AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider> { public abstract class DiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public readonly TCodeStyleProvider _codeStyleProvider; protected DiagnosticAnalyzer(bool isUnnecessary = true, bool configurable = true) : this(new TCodeStyleProvider(), isUnnecessary, configurable) { } private DiagnosticAnalyzer(TCodeStyleProvider codeStyleProvider, bool isUnnecessary, bool configurable) : base(codeStyleProvider._descriptorId, codeStyleProvider._enforceOnBuild, codeStyleProvider._option, codeStyleProvider._language, codeStyleProvider._title, codeStyleProvider._message, isUnnecessary, configurable) { _codeStyleProvider = codeStyleProvider; } protected sealed override void InitializeWorker(Diagnostics.AnalysisContext context) => _codeStyleProvider.DiagnosticAnalyzerInitialize(new AnalysisContext(_codeStyleProvider, context)); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => _codeStyleProvider.GetAnalyzerCategory(); } /// <summary> /// Critically, we want to consolidate the logic about checking if the analyzer should run /// at all. i.e. if the user has their option set to 'none' or 'refactoring only' then we /// do not want the analyzer to run at all. /// /// To that end, we don't let the subclass have direct access to the real <see /// cref="Diagnostics.AnalysisContext"/>. Instead, we pass this type to the subclass for it /// register with. We then check if the registration should proceed given the <see /// cref="CodeStyleOption2{T}"/> /// and the current <see cref="SyntaxTree"/> being processed. If not, we don't do the /// actual registration. /// </summary> protected struct AnalysisContext { private readonly TCodeStyleProvider _codeStyleProvider; private readonly Diagnostics.AnalysisContext _context; public AnalysisContext(TCodeStyleProvider codeStyleProvider, Diagnostics.AnalysisContext context) { _codeStyleProvider = codeStyleProvider; _context = context; } public void RegisterCompilationStartAction(Action<Compilation, AnalysisContext> analyze) { var _this = this; _context.RegisterCompilationStartAction( c => analyze(c.Compilation, _this)); } public void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext, CodeStyleOption2<TOptionKind>> analyze) { var provider = _codeStyleProvider; _context.RegisterCodeBlockAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken)); } public void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext, CodeStyleOption2<TOptionKind>> analyze) { var provider = _codeStyleProvider; _context.RegisterSemanticModelAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken)); } public void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext, CodeStyleOption2<TOptionKind>> analyze) { var provider = _codeStyleProvider; _context.RegisterSyntaxTreeAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.Tree, c.CancellationToken)); } public void RegisterOperationAction( Action<OperationAnalysisContext, CodeStyleOption2<TOptionKind>> analyze, params OperationKind[] operationKinds) { var provider = _codeStyleProvider; _context.RegisterOperationAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.Operation.SemanticModel.SyntaxTree, c.CancellationToken), operationKinds); } public void RegisterSyntaxNodeAction<TSyntaxKind>( Action<SyntaxNodeAnalysisContext, CodeStyleOption2<TOptionKind>> analyze, params TSyntaxKind[] syntaxKinds) where TSyntaxKind : struct { var provider = _codeStyleProvider; _context.RegisterSyntaxNodeAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken), syntaxKinds); } private static void AnalyzeIfEnabled<TContext>( TCodeStyleProvider provider, TContext context, Action<TContext, CodeStyleOption2<TOptionKind>> analyze, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionValue = options.GetOption(provider._option, syntaxTree, cancellationToken); var severity = GetOptionSeverity(optionValue); switch (severity) { case ReportDiagnostic.Error: case ReportDiagnostic.Warn: case ReportDiagnostic.Info: break; default: // don't analyze if it's any other value. return; } analyze(context, optionValue); } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectShim.OptionsProcessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal partial class CSharpProjectShim { private class OptionsProcessor : VisualStudioProjectOptionsProcessor { private readonly VisualStudioProject _visualStudioProject; private readonly object[] _options = new object[(int)CompilerOptions.LARGEST_OPTION_ID]; private string? _mainTypeName; private OutputKind _outputKind; public OptionsProcessor(VisualStudioProject visualStudioProject, HostWorkspaceServices workspaceServices) : base(visualStudioProject, workspaceServices) { _visualStudioProject = visualStudioProject; } public object this[CompilerOptions compilerOption] { get { return _options[(int)compilerOption]; } set { if (object.Equals(_options[(int)compilerOption], value)) { return; } _options[(int)compilerOption] = value; UpdateProjectForNewHostValues(); } } protected override CompilationOptions ComputeCompilationOptionsWithHostValues(CompilationOptions compilationOptions, IRuleSetFile? ruleSetFile) { IDictionary<string, ReportDiagnostic>? ruleSetSpecificDiagnosticOptions; // Get options from the ruleset file, if any, first. That way project-specific // options can override them. ReportDiagnostic? ruleSetGeneralDiagnosticOption = null; // TODO: merge this core logic back down to the base of OptionsProcessor, since this should be the same for all languages. The CompilationOptions // would then already contain the right information, and could be updated accordingly by the language-specific logic. if (ruleSetFile != null) { ruleSetGeneralDiagnosticOption = ruleSetFile.GetGeneralDiagnosticOption(); ruleSetSpecificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(ruleSetFile.GetSpecificDiagnosticOptions()); } else { ruleSetSpecificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(); } ReportDiagnostic generalDiagnosticOption; var warningsAreErrors = GetNullableBooleanOption(CompilerOptions.OPTID_WARNINGSAREERRORS); if (warningsAreErrors.HasValue) { generalDiagnosticOption = warningsAreErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default; } else if (ruleSetGeneralDiagnosticOption.HasValue) { generalDiagnosticOption = ruleSetGeneralDiagnosticOption.Value; } else { generalDiagnosticOption = ReportDiagnostic.Default; } // Start with the rule set options var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(ruleSetSpecificDiagnosticOptions); // Update the specific options based on the general settings if (warningsAreErrors.HasValue && warningsAreErrors.Value == true) { foreach (var pair in ruleSetSpecificDiagnosticOptions) { if (pair.Value == ReportDiagnostic.Warn) { diagnosticOptions[pair.Key] = ReportDiagnostic.Error; } } } // Update the specific options based on the specific settings foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNASERRORLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Error; } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNNOTASERRORLIST)) { if (ruleSetSpecificDiagnosticOptions.TryGetValue(diagnosticID, out var ruleSetOption)) { diagnosticOptions[diagnosticID] = ruleSetOption; } else { diagnosticOptions[diagnosticID] = ReportDiagnostic.Default; } } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_NOWARNLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Suppress; } if (!Enum.TryParse(GetStringOption(CompilerOptions.OPTID_PLATFORM, ""), ignoreCase: true, result: out Platform platform)) { platform = Platform.AnyCpu; } if (!int.TryParse(GetStringOption(CompilerOptions.OPTID_WARNINGLEVEL, defaultValue: ""), out var warningLevel)) { warningLevel = 4; } // TODO: appConfigPath: GetFilePathOption(CompilerOptions.OPTID_FUSIONCONFIG), bug #869604 return ((CSharpCompilationOptions)compilationOptions).WithAllowUnsafe(GetBooleanOption(CompilerOptions.OPTID_UNSAFE)) .WithOverflowChecks(GetBooleanOption(CompilerOptions.OPTID_CHECKED)) .WithCryptoKeyContainer(GetStringOption(CompilerOptions.OPTID_KEYNAME, defaultValue: null)) .WithCryptoKeyFile(GetFilePathRelativeOption(CompilerOptions.OPTID_KEYFILE)) .WithDelaySign(GetNullableBooleanOption(CompilerOptions.OPTID_DELAYSIGN)) .WithGeneralDiagnosticOption(generalDiagnosticOption) .WithMainTypeName(_mainTypeName) .WithModuleName(GetStringOption(CompilerOptions.OPTID_MODULEASSEMBLY, defaultValue: null)) .WithOptimizationLevel(GetBooleanOption(CompilerOptions.OPTID_OPTIMIZATIONS) ? OptimizationLevel.Release : OptimizationLevel.Debug) .WithOutputKind(_outputKind) .WithPlatform(platform) .WithSpecificDiagnosticOptions(diagnosticOptions) .WithWarningLevel(warningLevel); } private static string GetIdForErrorCode(int errorCode) => "CS" + errorCode.ToString("0000"); private IEnumerable<string> ParseWarningCodes(CompilerOptions compilerOptions) { Contract.ThrowIfFalse( compilerOptions == CompilerOptions.OPTID_NOWARNLIST || compilerOptions == CompilerOptions.OPTID_WARNASERRORLIST || compilerOptions == CompilerOptions.OPTID_WARNNOTASERRORLIST); foreach (var warning in GetStringOption(compilerOptions, defaultValue: "").Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries)) { var warningStringID = warning; if (int.TryParse(warning, out var warningId)) { warningStringID = GetIdForErrorCode(warningId); } yield return warningStringID; } } private bool? GetNullableBooleanOption(CompilerOptions optionID) => (bool?)_options[(int)optionID]; private bool GetBooleanOption(CompilerOptions optionID) => GetNullableBooleanOption(optionID).GetValueOrDefault(defaultValue: false); private string? GetFilePathRelativeOption(CompilerOptions optionID) { var path = GetStringOption(optionID, defaultValue: null); if (string.IsNullOrEmpty(path)) { return null; } var directory = Path.GetDirectoryName(_visualStudioProject.FilePath); if (!string.IsNullOrEmpty(directory)) { return FileUtilities.ResolveRelativePath(path, directory); } return null; } [return: NotNullIfNotNull("defaultValue")] private string? GetStringOption(CompilerOptions optionID, string? defaultValue) { var value = (string)_options[(int)optionID]; if (string.IsNullOrEmpty(value)) { return defaultValue; } else { return value; } } protected override ParseOptions ComputeParseOptionsWithHostValues(ParseOptions parseOptions) { var symbols = GetStringOption(CompilerOptions.OPTID_CCSYMBOLS, defaultValue: "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // The base implementation of OptionsProcessor already tried this, but it didn't have the real documentation // path so we have to do it a second time var documentationMode = DocumentationMode.Parse; if (GetStringOption(CompilerOptions.OPTID_XML_DOCFILE, defaultValue: null) != null) { documentationMode = DocumentationMode.Diagnose; } LanguageVersionFacts.TryParse(GetStringOption(CompilerOptions.OPTID_COMPATIBILITY, defaultValue: ""), out var languageVersion); return ((CSharpParseOptions)parseOptions).WithKind(SourceCodeKind.Regular) .WithLanguageVersion(languageVersion) .WithPreprocessorSymbols(symbols.AsImmutable()) .WithDocumentationMode(documentationMode); } public void SetOutputFileType(OutputFileType fileType) { var newOutputKind = fileType switch { OutputFileType.Console => OutputKind.ConsoleApplication, OutputFileType.Windows => OutputKind.WindowsApplication, OutputFileType.Library => OutputKind.DynamicallyLinkedLibrary, OutputFileType.Module => OutputKind.NetModule, OutputFileType.AppContainer => OutputKind.WindowsRuntimeApplication, OutputFileType.WinMDObj => OutputKind.WindowsRuntimeMetadata, _ => throw new ArgumentException("fileType was not a valid OutputFileType", nameof(fileType)), }; if (_outputKind != newOutputKind) { _outputKind = newOutputKind; UpdateProjectForNewHostValues(); } } public void SetMainTypeName(string? mainTypeName) { if (_mainTypeName != mainTypeName) { _mainTypeName = mainTypeName; UpdateProjectForNewHostValues(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal partial class CSharpProjectShim { private class OptionsProcessor : VisualStudioProjectOptionsProcessor { private readonly VisualStudioProject _visualStudioProject; private readonly object[] _options = new object[(int)CompilerOptions.LARGEST_OPTION_ID]; private string? _mainTypeName; private OutputKind _outputKind; public OptionsProcessor(VisualStudioProject visualStudioProject, HostWorkspaceServices workspaceServices) : base(visualStudioProject, workspaceServices) { _visualStudioProject = visualStudioProject; } public object this[CompilerOptions compilerOption] { get { return _options[(int)compilerOption]; } set { if (object.Equals(_options[(int)compilerOption], value)) { return; } _options[(int)compilerOption] = value; UpdateProjectForNewHostValues(); } } protected override CompilationOptions ComputeCompilationOptionsWithHostValues(CompilationOptions compilationOptions, IRuleSetFile? ruleSetFile) { IDictionary<string, ReportDiagnostic>? ruleSetSpecificDiagnosticOptions; // Get options from the ruleset file, if any, first. That way project-specific // options can override them. ReportDiagnostic? ruleSetGeneralDiagnosticOption = null; // TODO: merge this core logic back down to the base of OptionsProcessor, since this should be the same for all languages. The CompilationOptions // would then already contain the right information, and could be updated accordingly by the language-specific logic. if (ruleSetFile != null) { ruleSetGeneralDiagnosticOption = ruleSetFile.GetGeneralDiagnosticOption(); ruleSetSpecificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(ruleSetFile.GetSpecificDiagnosticOptions()); } else { ruleSetSpecificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(); } ReportDiagnostic generalDiagnosticOption; var warningsAreErrors = GetNullableBooleanOption(CompilerOptions.OPTID_WARNINGSAREERRORS); if (warningsAreErrors.HasValue) { generalDiagnosticOption = warningsAreErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default; } else if (ruleSetGeneralDiagnosticOption.HasValue) { generalDiagnosticOption = ruleSetGeneralDiagnosticOption.Value; } else { generalDiagnosticOption = ReportDiagnostic.Default; } // Start with the rule set options var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(ruleSetSpecificDiagnosticOptions); // Update the specific options based on the general settings if (warningsAreErrors.HasValue && warningsAreErrors.Value == true) { foreach (var pair in ruleSetSpecificDiagnosticOptions) { if (pair.Value == ReportDiagnostic.Warn) { diagnosticOptions[pair.Key] = ReportDiagnostic.Error; } } } // Update the specific options based on the specific settings foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNASERRORLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Error; } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNNOTASERRORLIST)) { if (ruleSetSpecificDiagnosticOptions.TryGetValue(diagnosticID, out var ruleSetOption)) { diagnosticOptions[diagnosticID] = ruleSetOption; } else { diagnosticOptions[diagnosticID] = ReportDiagnostic.Default; } } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_NOWARNLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Suppress; } if (!Enum.TryParse(GetStringOption(CompilerOptions.OPTID_PLATFORM, ""), ignoreCase: true, result: out Platform platform)) { platform = Platform.AnyCpu; } if (!int.TryParse(GetStringOption(CompilerOptions.OPTID_WARNINGLEVEL, defaultValue: ""), out var warningLevel)) { warningLevel = 4; } // TODO: appConfigPath: GetFilePathOption(CompilerOptions.OPTID_FUSIONCONFIG), bug #869604 return ((CSharpCompilationOptions)compilationOptions).WithAllowUnsafe(GetBooleanOption(CompilerOptions.OPTID_UNSAFE)) .WithOverflowChecks(GetBooleanOption(CompilerOptions.OPTID_CHECKED)) .WithCryptoKeyContainer(GetStringOption(CompilerOptions.OPTID_KEYNAME, defaultValue: null)) .WithCryptoKeyFile(GetFilePathRelativeOption(CompilerOptions.OPTID_KEYFILE)) .WithDelaySign(GetNullableBooleanOption(CompilerOptions.OPTID_DELAYSIGN)) .WithGeneralDiagnosticOption(generalDiagnosticOption) .WithMainTypeName(_mainTypeName) .WithModuleName(GetStringOption(CompilerOptions.OPTID_MODULEASSEMBLY, defaultValue: null)) .WithOptimizationLevel(GetBooleanOption(CompilerOptions.OPTID_OPTIMIZATIONS) ? OptimizationLevel.Release : OptimizationLevel.Debug) .WithOutputKind(_outputKind) .WithPlatform(platform) .WithSpecificDiagnosticOptions(diagnosticOptions) .WithWarningLevel(warningLevel); } private static string GetIdForErrorCode(int errorCode) => "CS" + errorCode.ToString("0000"); private IEnumerable<string> ParseWarningCodes(CompilerOptions compilerOptions) { Contract.ThrowIfFalse( compilerOptions == CompilerOptions.OPTID_NOWARNLIST || compilerOptions == CompilerOptions.OPTID_WARNASERRORLIST || compilerOptions == CompilerOptions.OPTID_WARNNOTASERRORLIST); foreach (var warning in GetStringOption(compilerOptions, defaultValue: "").Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries)) { var warningStringID = warning; if (int.TryParse(warning, out var warningId)) { warningStringID = GetIdForErrorCode(warningId); } yield return warningStringID; } } private bool? GetNullableBooleanOption(CompilerOptions optionID) => (bool?)_options[(int)optionID]; private bool GetBooleanOption(CompilerOptions optionID) => GetNullableBooleanOption(optionID).GetValueOrDefault(defaultValue: false); private string? GetFilePathRelativeOption(CompilerOptions optionID) { var path = GetStringOption(optionID, defaultValue: null); if (string.IsNullOrEmpty(path)) { return null; } var directory = Path.GetDirectoryName(_visualStudioProject.FilePath); if (!string.IsNullOrEmpty(directory)) { return FileUtilities.ResolveRelativePath(path, directory); } return null; } [return: NotNullIfNotNull("defaultValue")] private string? GetStringOption(CompilerOptions optionID, string? defaultValue) { var value = (string)_options[(int)optionID]; if (string.IsNullOrEmpty(value)) { return defaultValue; } else { return value; } } protected override ParseOptions ComputeParseOptionsWithHostValues(ParseOptions parseOptions) { var symbols = GetStringOption(CompilerOptions.OPTID_CCSYMBOLS, defaultValue: "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // The base implementation of OptionsProcessor already tried this, but it didn't have the real documentation // path so we have to do it a second time var documentationMode = DocumentationMode.Parse; if (GetStringOption(CompilerOptions.OPTID_XML_DOCFILE, defaultValue: null) != null) { documentationMode = DocumentationMode.Diagnose; } LanguageVersionFacts.TryParse(GetStringOption(CompilerOptions.OPTID_COMPATIBILITY, defaultValue: ""), out var languageVersion); return ((CSharpParseOptions)parseOptions).WithKind(SourceCodeKind.Regular) .WithLanguageVersion(languageVersion) .WithPreprocessorSymbols(symbols.AsImmutable()) .WithDocumentationMode(documentationMode); } public void SetOutputFileType(OutputFileType fileType) { var newOutputKind = fileType switch { OutputFileType.Console => OutputKind.ConsoleApplication, OutputFileType.Windows => OutputKind.WindowsApplication, OutputFileType.Library => OutputKind.DynamicallyLinkedLibrary, OutputFileType.Module => OutputKind.NetModule, OutputFileType.AppContainer => OutputKind.WindowsRuntimeApplication, OutputFileType.WinMDObj => OutputKind.WindowsRuntimeMetadata, _ => throw new ArgumentException("fileType was not a valid OutputFileType", nameof(fileType)), }; if (_outputKind != newOutputKind) { _outputKind = newOutputKind; UpdateProjectForNewHostValues(); } } public void SetMainTypeName(string? mainTypeName) { if (_mainTypeName != mainTypeName) { _mainTypeName = mainTypeName; UpdateProjectForNewHostValues(); } } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedAccessorValueParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents the compiler generated value parameter for property/event accessor. /// This parameter has no source location/syntax, but may have attributes. /// Attributes with 'param' target specifier on the accessor must be applied to the this parameter. /// </summary> internal sealed class SynthesizedAccessorValueParameterSymbol : SourceComplexParameterSymbol { public SynthesizedAccessorValueParameterSymbol(SourceMemberMethodSymbol accessor, TypeWithAnnotations paramType, int ordinal) : base(accessor, ordinal, paramType, RefKind.None, ParameterSymbol.ValueParameterName, accessor.Locations, syntaxRef: null, isParams: false, isExtensionMethodThis: false) { } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { var result = FlowAnalysisAnnotations.None; if (ContainingSymbol is SourcePropertyAccessorSymbol propertyAccessor && propertyAccessor.AssociatedSymbol is SourcePropertySymbolBase property) { if (property.HasDisallowNull) { result |= FlowAnalysisAnnotations.DisallowNull; } if (property.HasAllowNull) { result |= FlowAnalysisAnnotations.AllowNull; } } return result; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; // since RefKind is always None. } } public override bool IsImplicitlyDeclared { get { return true; } } protected override IAttributeTargetSymbol AttributeOwner { get { return (SourceMemberMethodSymbol)this.ContainingSymbol; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // Bind the attributes on the accessor's attribute syntax list with "param" target specifier. var accessor = (SourceMemberMethodSymbol)this.ContainingSymbol; return accessor.GetAttributeDeclarations(); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol is SourcePropertyAccessorSymbol propertyAccessor && propertyAccessor.AssociatedSymbol is SourcePropertySymbolBase property) { var annotations = FlowAnalysisAnnotations; if ((annotations & FlowAnalysisAnnotations.DisallowNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(property.DisallowNullAttributeIfExists)); } if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(property.AllowNullAttributeIfExists)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents the compiler generated value parameter for property/event accessor. /// This parameter has no source location/syntax, but may have attributes. /// Attributes with 'param' target specifier on the accessor must be applied to the this parameter. /// </summary> internal sealed class SynthesizedAccessorValueParameterSymbol : SourceComplexParameterSymbol { public SynthesizedAccessorValueParameterSymbol(SourceMemberMethodSymbol accessor, TypeWithAnnotations paramType, int ordinal) : base(accessor, ordinal, paramType, RefKind.None, ParameterSymbol.ValueParameterName, accessor.Locations, syntaxRef: null, isParams: false, isExtensionMethodThis: false) { } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { var result = FlowAnalysisAnnotations.None; if (ContainingSymbol is SourcePropertyAccessorSymbol propertyAccessor && propertyAccessor.AssociatedSymbol is SourcePropertySymbolBase property) { if (property.HasDisallowNull) { result |= FlowAnalysisAnnotations.DisallowNull; } if (property.HasAllowNull) { result |= FlowAnalysisAnnotations.AllowNull; } } return result; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; // since RefKind is always None. } } public override bool IsImplicitlyDeclared { get { return true; } } protected override IAttributeTargetSymbol AttributeOwner { get { return (SourceMemberMethodSymbol)this.ContainingSymbol; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // Bind the attributes on the accessor's attribute syntax list with "param" target specifier. var accessor = (SourceMemberMethodSymbol)this.ContainingSymbol; return accessor.GetAttributeDeclarations(); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol is SourcePropertyAccessorSymbol propertyAccessor && propertyAccessor.AssociatedSymbol is SourcePropertySymbolBase property) { var annotations = FlowAnalysisAnnotations; if ((annotations & FlowAnalysisAnnotations.DisallowNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(property.DisallowNullAttributeIfExists)); } if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { AddSynthesizedAttribute(ref attributes, new SynthesizedAttributeData(property.AllowNullAttributeIfExists)); } } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/SignatureHelp/ConstructorInitializerSignatureHelpProvider.cs
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("ConstructorInitializerSignatureHelpProvider", LanguageNames.CSharp), Shared] internal partial class ConstructorInitializerSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConstructorInitializerSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => ch == '(' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetConstructorInitializer(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ConstructorInitializerSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<ConstructorInitializerSyntax>(token, IsTriggerCharacter); private static bool IsArgumentListToken(ConstructorInitializerSyntax expression, SyntaxToken token) { return expression.ArgumentList != null && expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetConstructorInitializer(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var constructorInitializer)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedType(position, cancellationToken); if (within == null) { return null; } if (within.TypeKind != TypeKind.Struct && within.TypeKind != TypeKind.Class) { return null; } var type = constructorInitializer.Kind() == SyntaxKind.BaseConstructorInitializer ? within.BaseType : within; if (type == null) { return null; } var currentConstructor = semanticModel.GetDeclaredSymbol(constructorInitializer.Parent!, cancellationToken); var accessibleConstructors = type.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(within) && !c.Equals(currentConstructor)) .WhereAsArray(c => c.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) .Sort(semanticModel, constructorInitializer.SpanStart); if (!accessibleConstructors.Any()) { return null; } var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(constructorInitializer.ArgumentList); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var symbolInfo = semanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); var selectedItem = TryGetSelectedIndex(accessibleConstructors, symbolInfo.Symbol); return CreateSignatureHelpItems(accessibleConstructors.SelectAsArray(c => Convert(c, constructorInitializer.ArgumentList.OpenParenToken, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetConstructorInitializer(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } return null; } private static SignatureHelpItem Convert( IMethodSymbol constructor, SyntaxToken openToken, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = openToken.SpanStart; var item = CreateItem( constructor, semanticModel, position, anonymousTypeDisplayService, constructor.IsParams(), constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(constructor, semanticModel, position), GetSeparatorParts(), GetPostambleParts(), constructor.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; } private static IList<SymbolDisplayPart> GetPreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } private static IList<SymbolDisplayPart> GetPostambleParts() { return SpecializedCollections.SingletonList( Punctuation(SyntaxKind.CloseParenToken)); } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("ConstructorInitializerSignatureHelpProvider", LanguageNames.CSharp), Shared] internal partial class ConstructorInitializerSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConstructorInitializerSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => ch == '(' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetConstructorInitializer(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ConstructorInitializerSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<ConstructorInitializerSyntax>(token, IsTriggerCharacter); private static bool IsArgumentListToken(ConstructorInitializerSyntax expression, SyntaxToken token) { return expression.ArgumentList != null && expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetConstructorInitializer(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var constructorInitializer)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedType(position, cancellationToken); if (within == null) { return null; } if (within.TypeKind != TypeKind.Struct && within.TypeKind != TypeKind.Class) { return null; } var type = constructorInitializer.Kind() == SyntaxKind.BaseConstructorInitializer ? within.BaseType : within; if (type == null) { return null; } var currentConstructor = semanticModel.GetDeclaredSymbol(constructorInitializer.Parent!, cancellationToken); var accessibleConstructors = type.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(within) && !c.Equals(currentConstructor)) .WhereAsArray(c => c.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) .Sort(semanticModel, constructorInitializer.SpanStart); if (!accessibleConstructors.Any()) { return null; } var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(constructorInitializer.ArgumentList); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var symbolInfo = semanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); var selectedItem = TryGetSelectedIndex(accessibleConstructors, symbolInfo.Symbol); return CreateSignatureHelpItems(accessibleConstructors.SelectAsArray(c => Convert(c, constructorInitializer.ArgumentList.OpenParenToken, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetConstructorInitializer(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } return null; } private static SignatureHelpItem Convert( IMethodSymbol constructor, SyntaxToken openToken, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = openToken.SpanStart; var item = CreateItem( constructor, semanticModel, position, anonymousTypeDisplayService, constructor.IsParams(), constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(constructor, semanticModel, position), GetSeparatorParts(), GetPostambleParts(), constructor.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; } private static IList<SymbolDisplayPart> GetPreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } private static IList<SymbolDisplayPart> GetPostambleParts() { return SpecializedCollections.SingletonList( Punctuation(SyntaxKind.CloseParenToken)); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.SimplifyInterpolation; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.SimplifyInterpolation { internal sealed class CSharpSimplifyInterpolationHelpers : AbstractSimplifyInterpolationHelpers { public static CSharpSimplifyInterpolationHelpers Instance { get; } = new(); private CSharpSimplifyInterpolationHelpers() { } protected override bool PermitNonLiteralAlignmentComponents => true; protected override SyntaxNode GetPreservedInterpolationExpressionSyntax(IOperation operation) { return operation.Syntax switch { ConditionalExpressionSyntax { Parent: ParenthesizedExpressionSyntax parent } => parent, var syntax => syntax, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.SimplifyInterpolation; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.SimplifyInterpolation { internal sealed class CSharpSimplifyInterpolationHelpers : AbstractSimplifyInterpolationHelpers { public static CSharpSimplifyInterpolationHelpers Instance { get; } = new(); private CSharpSimplifyInterpolationHelpers() { } protected override bool PermitNonLiteralAlignmentComponents => true; protected override SyntaxNode GetPreservedInterpolationExpressionSyntax(IOperation operation) { return operation.Syntax switch { ConditionalExpressionSyntax { Parent: ParenthesizedExpressionSyntax parent } => parent, var syntax => syntax, }; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SimpleIntervalTreeExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SimpleIntervalTreeExtensions { /// <summary> /// check whether the given span is intersects with the tree /// </summary> public static bool HasIntervalThatIntersectsWith(this SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> tree, TextSpan span) => tree.HasIntervalThatIntersectsWith(span.Start, span.Length); } }
// Licensed to the .NET Foundation under one or more 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.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SimpleIntervalTreeExtensions { /// <summary> /// check whether the given span is intersects with the tree /// </summary> public static bool HasIntervalThatIntersectsWith(this SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> tree, TextSpan span) => tree.HasIntervalThatIntersectsWith(span.Start, span.Length); } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceGeneratedFileInfo.cs
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal sealed class MetadataAsSourceGeneratedFileInfo { public readonly ProjectId SourceProjectId; public readonly Workspace Workspace; public readonly AssemblyIdentity AssemblyIdentity; public readonly string LanguageName; public readonly ImmutableArray<MetadataReference> References; public readonly string TemporaryFilePath; private readonly ParseOptions? _parseOptions; public MetadataAsSourceGeneratedFileInfo(string rootPath, Project sourceProject, INamedTypeSymbol topLevelNamedType, bool allowDecompilation) { this.SourceProjectId = sourceProject.Id; this.Workspace = sourceProject.Solution.Workspace; this.LanguageName = allowDecompilation ? LanguageNames.CSharp : sourceProject.Language; if (sourceProject.Language == LanguageName) { _parseOptions = sourceProject.ParseOptions; } else { _parseOptions = Workspace.Services.GetLanguageServices(LanguageName).GetRequiredService<ISyntaxTreeFactoryService>().GetDefaultParseOptionsWithLatestLanguageVersion(); } this.References = sourceProject.MetadataReferences.ToImmutableArray(); this.AssemblyIdentity = topLevelNamedType.ContainingAssembly.Identity; var extension = LanguageName == LanguageNames.CSharp ? ".cs" : ".vb"; var directoryName = Guid.NewGuid().ToString("N"); this.TemporaryFilePath = Path.Combine(rootPath, directoryName, topLevelNamedType.Name + extension); } public static Encoding Encoding => Encoding.UTF8; /// <summary> /// Creates a ProjectInfo to represent the fake project created for metadata as source documents. /// </summary> /// <param name="workspace">The containing workspace.</param> /// <param name="loadFileFromDisk">Whether the source file already exists on disk and should be included. If /// this is a false, a document is still created, but it's not backed by the file system and thus we won't /// try to load it.</param> public Tuple<ProjectInfo, DocumentId> GetProjectInfoAndDocumentId(Workspace workspace, bool loadFileFromDisk) { var projectId = ProjectId.CreateNewId(); // Just say it's always a DLL since we probably won't have a Main method var compilationOptions = workspace.Services.GetLanguageServices(LanguageName).CompilationFactory!.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var extension = LanguageName == LanguageNames.CSharp ? ".cs" : ".vb"; // We need to include the version information of the assembly so InternalsVisibleTo and stuff works var assemblyInfoDocumentId = DocumentId.CreateNewId(projectId); var assemblyInfoFileName = "AssemblyInfo" + extension; var assemblyInfoString = LanguageName == LanguageNames.CSharp ? string.Format(@"[assembly: System.Reflection.AssemblyVersion(""{0}"")]", AssemblyIdentity.Version) : string.Format(@"<Assembly: System.Reflection.AssemblyVersion(""{0}"")>", AssemblyIdentity.Version); var assemblyInfoSourceTextContainer = SourceText.From(assemblyInfoString, Encoding).Container; var assemblyInfoDocument = DocumentInfo.Create( assemblyInfoDocumentId, assemblyInfoFileName, loader: TextLoader.From(assemblyInfoSourceTextContainer, VersionStamp.Default)); var generatedDocumentId = DocumentId.CreateNewId(projectId); var generatedDocument = DocumentInfo.Create( generatedDocumentId, Path.GetFileName(TemporaryFilePath), filePath: TemporaryFilePath, loader: loadFileFromDisk ? new FileTextLoader(TemporaryFilePath, Encoding) : null); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Default, name: AssemblyIdentity.Name, assemblyName: AssemblyIdentity.Name, language: LanguageName, compilationOptions: compilationOptions, parseOptions: _parseOptions, documents: new[] { assemblyInfoDocument, generatedDocument }, metadataReferences: References); return Tuple.Create(projectInfo, generatedDocumentId); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal sealed class MetadataAsSourceGeneratedFileInfo { public readonly ProjectId SourceProjectId; public readonly Workspace Workspace; public readonly AssemblyIdentity AssemblyIdentity; public readonly string LanguageName; public readonly ImmutableArray<MetadataReference> References; public readonly string TemporaryFilePath; private readonly ParseOptions? _parseOptions; public MetadataAsSourceGeneratedFileInfo(string rootPath, Project sourceProject, INamedTypeSymbol topLevelNamedType, bool allowDecompilation) { this.SourceProjectId = sourceProject.Id; this.Workspace = sourceProject.Solution.Workspace; this.LanguageName = allowDecompilation ? LanguageNames.CSharp : sourceProject.Language; if (sourceProject.Language == LanguageName) { _parseOptions = sourceProject.ParseOptions; } else { _parseOptions = Workspace.Services.GetLanguageServices(LanguageName).GetRequiredService<ISyntaxTreeFactoryService>().GetDefaultParseOptionsWithLatestLanguageVersion(); } this.References = sourceProject.MetadataReferences.ToImmutableArray(); this.AssemblyIdentity = topLevelNamedType.ContainingAssembly.Identity; var extension = LanguageName == LanguageNames.CSharp ? ".cs" : ".vb"; var directoryName = Guid.NewGuid().ToString("N"); this.TemporaryFilePath = Path.Combine(rootPath, directoryName, topLevelNamedType.Name + extension); } public static Encoding Encoding => Encoding.UTF8; /// <summary> /// Creates a ProjectInfo to represent the fake project created for metadata as source documents. /// </summary> /// <param name="workspace">The containing workspace.</param> /// <param name="loadFileFromDisk">Whether the source file already exists on disk and should be included. If /// this is a false, a document is still created, but it's not backed by the file system and thus we won't /// try to load it.</param> public Tuple<ProjectInfo, DocumentId> GetProjectInfoAndDocumentId(Workspace workspace, bool loadFileFromDisk) { var projectId = ProjectId.CreateNewId(); // Just say it's always a DLL since we probably won't have a Main method var compilationOptions = workspace.Services.GetLanguageServices(LanguageName).CompilationFactory!.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var extension = LanguageName == LanguageNames.CSharp ? ".cs" : ".vb"; // We need to include the version information of the assembly so InternalsVisibleTo and stuff works var assemblyInfoDocumentId = DocumentId.CreateNewId(projectId); var assemblyInfoFileName = "AssemblyInfo" + extension; var assemblyInfoString = LanguageName == LanguageNames.CSharp ? string.Format(@"[assembly: System.Reflection.AssemblyVersion(""{0}"")]", AssemblyIdentity.Version) : string.Format(@"<Assembly: System.Reflection.AssemblyVersion(""{0}"")>", AssemblyIdentity.Version); var assemblyInfoSourceTextContainer = SourceText.From(assemblyInfoString, Encoding).Container; var assemblyInfoDocument = DocumentInfo.Create( assemblyInfoDocumentId, assemblyInfoFileName, loader: TextLoader.From(assemblyInfoSourceTextContainer, VersionStamp.Default)); var generatedDocumentId = DocumentId.CreateNewId(projectId); var generatedDocument = DocumentInfo.Create( generatedDocumentId, Path.GetFileName(TemporaryFilePath), filePath: TemporaryFilePath, loader: loadFileFromDisk ? new FileTextLoader(TemporaryFilePath, Encoding) : null); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Default, name: AssemblyIdentity.Name, assemblyName: AssemblyIdentity.Name, language: LanguageName, compilationOptions: compilationOptions, parseOptions: _parseOptions, documents: new[] { assemblyInfoDocument, generatedDocument }, metadataReferences: References); return Tuple.Create(projectInfo, generatedDocumentId); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Declarations/DeclarationModifiers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.CSharp { [Flags] internal enum DeclarationModifiers : uint { None = 0, Abstract = 1 << 0, Sealed = 1 << 1, Static = 1 << 2, New = 1 << 3, Public = 1 << 4, Protected = 1 << 5, Internal = 1 << 6, ProtectedInternal = 1 << 7, // the two keywords together are treated as one modifier Private = 1 << 8, PrivateProtected = 1 << 9, // the two keywords together are treated as one modifier ReadOnly = 1 << 10, Const = 1 << 11, Volatile = 1 << 12, Extern = 1 << 13, Partial = 1 << 14, Unsafe = 1 << 15, Fixed = 1 << 16, Virtual = 1 << 17, // used for method binding Override = 1 << 18, // used for method binding Indexer = 1 << 19, // not a real modifier, but used to record that indexer syntax was used. Async = 1 << 20, Ref = 1 << 21, // used only for structs All = (1 << 23) - 1, // all modifiers Unset = 1 << 23, // used when a modifiers value hasn't yet been computed AccessibilityMask = PrivateProtected | Private | Protected | Internal | ProtectedInternal | Public, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.CSharp { [Flags] internal enum DeclarationModifiers : uint { None = 0, Abstract = 1 << 0, Sealed = 1 << 1, Static = 1 << 2, New = 1 << 3, Public = 1 << 4, Protected = 1 << 5, Internal = 1 << 6, ProtectedInternal = 1 << 7, // the two keywords together are treated as one modifier Private = 1 << 8, PrivateProtected = 1 << 9, // the two keywords together are treated as one modifier ReadOnly = 1 << 10, Const = 1 << 11, Volatile = 1 << 12, Extern = 1 << 13, Partial = 1 << 14, Unsafe = 1 << 15, Fixed = 1 << 16, Virtual = 1 << 17, // used for method binding Override = 1 << 18, // used for method binding Indexer = 1 << 19, // not a real modifier, but used to record that indexer syntax was used. Async = 1 << 20, Ref = 1 << 21, // used only for structs All = (1 << 23) - 1, // all modifiers Unset = 1 << 23, // used when a modifiers value hasn't yet been computed AccessibilityMask = PrivateProtected | Private | Protected | Internal | ProtectedInternal | Public, } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Debugging/Resources/ProximityExpressionsGetterTestFile.cs
using System.Collections.Generic; using Roslyn.Compilers.CSharp; using Roslyn.Services.CSharp.Utilities; using Roslyn.Services.Internal.Extensions; namespace Roslyn.Services.CSharp.Debugging { internal partial class ProximityExpressionsGetter { private static string ConvertToString(ExpressionSyntax expression) { // TODO(cyrusn): Should we strip out comments? return expression.GetFullText(); } private static void CollectExpressionTerms(int position, ExpressionSyntax expression, List<string> terms) { // Check here rather than at all the call sites... if (expression == null) { return; } // Collect terms from this expression, which returns flags indicating the validity // of this expression as a whole. var expressionType = ExpressionType.Invalid; CollectExpressionTerms(position, expression, terms, ref expressionType); if ((expressionType & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { // If this expression identified itself as a valid term, add it to the // term table terms.Add(ConvertToString(expression)); } } private static void CollectExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Check here rather than at all the call sites... if (expression == null) { return; } switch (expression.Kind) { case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: // an op term is ok if it's a "this" or "base" op it allows us to see // "this.goo" in the autos window note: it's not a VALIDTERM since we don't // want "this" showing up in the auto's window twice. expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.IdentifierName: // Name nodes are always valid terms expressionType = ExpressionType.ValidTerm; return; case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: // Constants can make up a valid term, but we don't consider them valid // terms themselves (since we don't want them to show up in the autos window // on their own). expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.CastExpression: // For a cast, just add the nested expression. Note: this is technically // unsafe as the cast *may* have side effects. However, in practice this is // extremely rare, so we allow for this since it's ok in the common case. CollectExpressionTerms(position, ((CastExpressionSyntax)expression).Expression, terms, ref expressionType); return; case SyntaxKind.MemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: CollectMemberAccessExpressionTerms(position, expression, terms, ref expressionType); return; case SyntaxKind.ObjectCreationExpression: CollectObjectCreationExpressionTerms(position, expression, terms, ref expressionType); return; case SyntaxKind.ArrayCreationExpression: CollectArrayCreationExpressionTerms(position, expression, terms, ref expressionType); return; case SyntaxKind.InvocationExpression: CollectInvocationExpressionTerms(position, expression, terms, ref expressionType); return; } // +, -, ++, --, !, etc. // // This is a valid expression if it doesn't have obvious side effects (i.e. ++, --) if (expression is PrefixUnaryExpressionSyntax) { CollectPrefixUnaryExpressionTerms(position, expression, terms, ref expressionType); return; } if (expression is PostfixUnaryExpressionSyntax) { CollectPostfixUnaryExpressionTerms(position, expression, terms, ref expressionType); return; } if (expression is BinaryExpressionSyntax) { CollectBinaryExpressionTerms(position, expression, terms, ref expressionType); return; } expressionType = ExpressionType.Invalid; } private static void CollectMemberAccessExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { var flags = ExpressionType.Invalid; // These operators always have a RHS of a name node, which we know would // "claim" to be a valid term, but is not valid without the LHS present. // So, we don't bother collecting anything from the RHS... var memberAccess = (MemberAccessExpressionSyntax)expression; CollectExpressionTerms(position, memberAccess.Expression, terms, ref flags); // If the LHS says it's a valid term, then we add it ONLY if our PARENT // is NOT another dot/arrow. This allows the expression 'a.b.c.d' to // add both 'a.b.c.d' and 'a.b.c', but not 'a.b' and 'a'. if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm && !expression.IsParentKind(SyntaxKind.MemberAccessExpression) && !expression.IsParentKind(SyntaxKind.PointerMemberAccessExpression)) { terms.Add(ConvertToString(memberAccess.Expression)); } // And this expression itself is a valid term if the LHS is a valid // expression, and its PARENT is not an invocation. if ((flags & ExpressionType.ValidExpression) == ExpressionType.ValidExpression && !expression.IsParentKind(SyntaxKind.InvocationExpression)) { expressionType = ExpressionType.ValidTerm; } else { expressionType = ExpressionType.ValidExpression; } } private static void CollectObjectCreationExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Object creation can *definitely* cause side effects. So we initially // mark this as something invalid. We allow it as a valid expr if all // the sub arguments are valid terms. expressionType = ExpressionType.Invalid; var objectionCreation = (ObjectCreationExpressionSyntax)expression; if (objectionCreation.ArgumentListOpt != null) { var flags = ExpressionType.Invalid; CollectArgumentTerms(position, objectionCreation.ArgumentListOpt, terms, ref flags); // If all arguments are terms, then this is possibly a valid expr // that can be used somewhere higher in the stack. if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { expressionType = ExpressionType.ValidExpression; } } } private static void CollectArrayCreationExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { var validTerm = true; var arrayCreation = (ArrayCreationExpressionSyntax)expression; if (arrayCreation.InitializerOpt != null) { var flags = ExpressionType.Invalid; arrayCreation.InitializerOpt.Expressions.Do(e => CollectExpressionTerms(position, e, terms, ref flags)); validTerm &= (flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm; } if (validTerm) { expressionType = ExpressionType.ValidExpression; } else { expressionType = ExpressionType.Invalid; } } private static void CollectInvocationExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Invocations definitely have side effects. So we assume this // is invalid initially expressionType = ExpressionType.Invalid; ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; var invocation = (InvocationExpressionSyntax)expression; CollectExpressionTerms(position, invocation.Expression, terms, ref leftFlags); CollectArgumentTerms(position, invocation.ArgumentList, terms, ref rightFlags); if ((leftFlags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(invocation.Expression)); } // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; } private static void CollectPrefixUnaryExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)expression; // Ask our subexpression for terms CollectExpressionTerms(position, prefixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(prefixUnaryExpression.Operand)); } if (expression.MatchesKind(SyntaxKind.LogicalNotExpression, SyntaxKind.BitwiseNotExpression, SyntaxKind.NegateExpression, SyntaxKind.PlusExpression)) { // We're a valid expression if our subexpression is... expressionType = flags & ExpressionType.ValidExpression; } } private static void CollectPostfixUnaryExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // ++ and -- are the only postfix operators. Since they always have side // effects, we never consider this an expression. expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; var postfixUnaryExpression = (PostfixUnaryExpressionSyntax)expression; // Ask our subexpression for terms CollectExpressionTerms(position, postfixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(postfixUnaryExpression.Operand)); } } private static void CollectBinaryExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; var binaryExpression = (BinaryExpressionSyntax)expression; CollectExpressionTerms(position, binaryExpression.Left, terms, ref leftFlags); CollectExpressionTerms(position, binaryExpression.Right, terms, ref rightFlags); if ((leftFlags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(binaryExpression.Left)); } if ((rightFlags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(binaryExpression.Right)); } // Many sorts of binops (like +=) will definitely have side effects. We only // consider this valid if it's a simple expression like +, -, etc. switch (binaryExpression.Kind) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.CoalesceExpression: // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; return; default: expressionType = ExpressionType.Invalid; return; } } private static void CollectArgumentTerms(int position, ArgumentListSyntax argumentList, IList<string> terms, ref ExpressionType expressionType) { var validExpr = true; // Process the list of expressions. This is probably a list of // arguments to a function call(or a list of array index expressions) foreach (var arg in argumentList.Arguments) { var flags = ExpressionType.Invalid; CollectExpressionTerms(position, arg.Expression, terms, ref flags); if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(arg.Expression)); } validExpr &= (flags & ExpressionType.ValidExpression) == ExpressionType.ValidExpression; } // We're never a valid term, but we're a valid expression if all // the list elements are... expressionType = validExpr ? ExpressionType.ValidExpression : 0; } private static void CollectVariableTerms(int position, SeparatedSyntaxList<VariableDeclaratorSyntax> declarators, List<string> terms) { foreach (var declarator in declarators) { if (declarator.InitializerOpt != null) { CollectExpressionTerms(position, declarator.InitializerOpt.Value, terms); } } } } }
using System.Collections.Generic; using Roslyn.Compilers.CSharp; using Roslyn.Services.CSharp.Utilities; using Roslyn.Services.Internal.Extensions; namespace Roslyn.Services.CSharp.Debugging { internal partial class ProximityExpressionsGetter { private static string ConvertToString(ExpressionSyntax expression) { // TODO(cyrusn): Should we strip out comments? return expression.GetFullText(); } private static void CollectExpressionTerms(int position, ExpressionSyntax expression, List<string> terms) { // Check here rather than at all the call sites... if (expression == null) { return; } // Collect terms from this expression, which returns flags indicating the validity // of this expression as a whole. var expressionType = ExpressionType.Invalid; CollectExpressionTerms(position, expression, terms, ref expressionType); if ((expressionType & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { // If this expression identified itself as a valid term, add it to the // term table terms.Add(ConvertToString(expression)); } } private static void CollectExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Check here rather than at all the call sites... if (expression == null) { return; } switch (expression.Kind) { case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: // an op term is ok if it's a "this" or "base" op it allows us to see // "this.goo" in the autos window note: it's not a VALIDTERM since we don't // want "this" showing up in the auto's window twice. expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.IdentifierName: // Name nodes are always valid terms expressionType = ExpressionType.ValidTerm; return; case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: // Constants can make up a valid term, but we don't consider them valid // terms themselves (since we don't want them to show up in the autos window // on their own). expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.CastExpression: // For a cast, just add the nested expression. Note: this is technically // unsafe as the cast *may* have side effects. However, in practice this is // extremely rare, so we allow for this since it's ok in the common case. CollectExpressionTerms(position, ((CastExpressionSyntax)expression).Expression, terms, ref expressionType); return; case SyntaxKind.MemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: CollectMemberAccessExpressionTerms(position, expression, terms, ref expressionType); return; case SyntaxKind.ObjectCreationExpression: CollectObjectCreationExpressionTerms(position, expression, terms, ref expressionType); return; case SyntaxKind.ArrayCreationExpression: CollectArrayCreationExpressionTerms(position, expression, terms, ref expressionType); return; case SyntaxKind.InvocationExpression: CollectInvocationExpressionTerms(position, expression, terms, ref expressionType); return; } // +, -, ++, --, !, etc. // // This is a valid expression if it doesn't have obvious side effects (i.e. ++, --) if (expression is PrefixUnaryExpressionSyntax) { CollectPrefixUnaryExpressionTerms(position, expression, terms, ref expressionType); return; } if (expression is PostfixUnaryExpressionSyntax) { CollectPostfixUnaryExpressionTerms(position, expression, terms, ref expressionType); return; } if (expression is BinaryExpressionSyntax) { CollectBinaryExpressionTerms(position, expression, terms, ref expressionType); return; } expressionType = ExpressionType.Invalid; } private static void CollectMemberAccessExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { var flags = ExpressionType.Invalid; // These operators always have a RHS of a name node, which we know would // "claim" to be a valid term, but is not valid without the LHS present. // So, we don't bother collecting anything from the RHS... var memberAccess = (MemberAccessExpressionSyntax)expression; CollectExpressionTerms(position, memberAccess.Expression, terms, ref flags); // If the LHS says it's a valid term, then we add it ONLY if our PARENT // is NOT another dot/arrow. This allows the expression 'a.b.c.d' to // add both 'a.b.c.d' and 'a.b.c', but not 'a.b' and 'a'. if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm && !expression.IsParentKind(SyntaxKind.MemberAccessExpression) && !expression.IsParentKind(SyntaxKind.PointerMemberAccessExpression)) { terms.Add(ConvertToString(memberAccess.Expression)); } // And this expression itself is a valid term if the LHS is a valid // expression, and its PARENT is not an invocation. if ((flags & ExpressionType.ValidExpression) == ExpressionType.ValidExpression && !expression.IsParentKind(SyntaxKind.InvocationExpression)) { expressionType = ExpressionType.ValidTerm; } else { expressionType = ExpressionType.ValidExpression; } } private static void CollectObjectCreationExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Object creation can *definitely* cause side effects. So we initially // mark this as something invalid. We allow it as a valid expr if all // the sub arguments are valid terms. expressionType = ExpressionType.Invalid; var objectionCreation = (ObjectCreationExpressionSyntax)expression; if (objectionCreation.ArgumentListOpt != null) { var flags = ExpressionType.Invalid; CollectArgumentTerms(position, objectionCreation.ArgumentListOpt, terms, ref flags); // If all arguments are terms, then this is possibly a valid expr // that can be used somewhere higher in the stack. if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { expressionType = ExpressionType.ValidExpression; } } } private static void CollectArrayCreationExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { var validTerm = true; var arrayCreation = (ArrayCreationExpressionSyntax)expression; if (arrayCreation.InitializerOpt != null) { var flags = ExpressionType.Invalid; arrayCreation.InitializerOpt.Expressions.Do(e => CollectExpressionTerms(position, e, terms, ref flags)); validTerm &= (flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm; } if (validTerm) { expressionType = ExpressionType.ValidExpression; } else { expressionType = ExpressionType.Invalid; } } private static void CollectInvocationExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Invocations definitely have side effects. So we assume this // is invalid initially expressionType = ExpressionType.Invalid; ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; var invocation = (InvocationExpressionSyntax)expression; CollectExpressionTerms(position, invocation.Expression, terms, ref leftFlags); CollectArgumentTerms(position, invocation.ArgumentList, terms, ref rightFlags); if ((leftFlags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(invocation.Expression)); } // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; } private static void CollectPrefixUnaryExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)expression; // Ask our subexpression for terms CollectExpressionTerms(position, prefixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(prefixUnaryExpression.Operand)); } if (expression.MatchesKind(SyntaxKind.LogicalNotExpression, SyntaxKind.BitwiseNotExpression, SyntaxKind.NegateExpression, SyntaxKind.PlusExpression)) { // We're a valid expression if our subexpression is... expressionType = flags & ExpressionType.ValidExpression; } } private static void CollectPostfixUnaryExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // ++ and -- are the only postfix operators. Since they always have side // effects, we never consider this an expression. expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; var postfixUnaryExpression = (PostfixUnaryExpressionSyntax)expression; // Ask our subexpression for terms CollectExpressionTerms(position, postfixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(postfixUnaryExpression.Operand)); } } private static void CollectBinaryExpressionTerms(int position, ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; var binaryExpression = (BinaryExpressionSyntax)expression; CollectExpressionTerms(position, binaryExpression.Left, terms, ref leftFlags); CollectExpressionTerms(position, binaryExpression.Right, terms, ref rightFlags); if ((leftFlags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(binaryExpression.Left)); } if ((rightFlags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(binaryExpression.Right)); } // Many sorts of binops (like +=) will definitely have side effects. We only // consider this valid if it's a simple expression like +, -, etc. switch (binaryExpression.Kind) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.CoalesceExpression: // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; return; default: expressionType = ExpressionType.Invalid; return; } } private static void CollectArgumentTerms(int position, ArgumentListSyntax argumentList, IList<string> terms, ref ExpressionType expressionType) { var validExpr = true; // Process the list of expressions. This is probably a list of // arguments to a function call(or a list of array index expressions) foreach (var arg in argumentList.Arguments) { var flags = ExpressionType.Invalid; CollectExpressionTerms(position, arg.Expression, terms, ref flags); if ((flags & ExpressionType.ValidTerm) == ExpressionType.ValidTerm) { terms.Add(ConvertToString(arg.Expression)); } validExpr &= (flags & ExpressionType.ValidExpression) == ExpressionType.ValidExpression; } // We're never a valid term, but we're a valid expression if all // the list elements are... expressionType = validExpr ? ExpressionType.ValidExpression : 0; } private static void CollectVariableTerms(int position, SeparatedSyntaxList<VariableDeclaratorSyntax> declarators, List<string> terms) { foreach (var declarator in declarators) { if (declarator.InitializerOpt != null) { CollectExpressionTerms(position, declarator.InitializerOpt.Value, terms); } } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Source/SourceModuleSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents the primary module of an assembly being built by compiler. /// </summary> internal sealed class SourceModuleSymbol : NonMissingModuleSymbol, IAttributeTargetSymbol { /// <summary> /// Owning assembly. /// </summary> private readonly SourceAssemblySymbol _assemblySymbol; private ImmutableArray<AssemblySymbol> _lazyAssembliesToEmbedTypesFrom; private ThreeState _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = ThreeState.Unknown; /// <summary> /// The declarations corresponding to the source files of this module. /// </summary> private readonly DeclarationTable _sources; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private ImmutableArray<Location> _locations; private NamespaceSymbol _globalNamespace; private bool _hasBadAttributes; internal SourceModuleSymbol( SourceAssemblySymbol assemblySymbol, DeclarationTable declarations, string moduleName) { Debug.Assert((object)assemblySymbol != null); _assemblySymbol = assemblySymbol; _sources = declarations; _name = moduleName; } internal void RecordPresenceOfBadAttributes() { _hasBadAttributes = true; } internal bool HasBadAttributes { get { return _hasBadAttributes; } } internal override int Ordinal { get { return 0; } } internal override Machine Machine { get { switch (DeclaringCompilation.Options.Platform) { case Platform.Arm: return Machine.ArmThumb2; case Platform.X64: return Machine.Amd64; case Platform.Arm64: return Machine.Arm64; case Platform.Itanium: return Machine.IA64; default: return Machine.I386; } } } internal override bool Bit32Required { get { return DeclaringCompilation.Options.Platform == Platform.X86; } } internal bool AnyReferencedAssembliesAreLinked { get { return GetAssembliesToEmbedTypesFrom().Length > 0; } } internal bool MightContainNoPiaLocalTypes() { return AnyReferencedAssembliesAreLinked || ContainsExplicitDefinitionOfNoPiaLocalTypes; } internal ImmutableArray<AssemblySymbol> GetAssembliesToEmbedTypesFrom() { if (_lazyAssembliesToEmbedTypesFrom.IsDefault) { AssertReferencesInitialized(); var buffer = ArrayBuilder<AssemblySymbol>.GetInstance(); foreach (AssemblySymbol asm in this.GetReferencedAssemblySymbols()) { if (asm.IsLinked) { buffer.Add(asm); } } ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssembliesToEmbedTypesFrom, buffer.ToImmutableAndFree(), default(ImmutableArray<AssemblySymbol>)); } Debug.Assert(!_lazyAssembliesToEmbedTypesFrom.IsDefault); return _lazyAssembliesToEmbedTypesFrom; } internal bool ContainsExplicitDefinitionOfNoPiaLocalTypes { get { if (_lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.Unknown) { _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(GlobalNamespace).ToThreeState(); } Debug.Assert(_lazyContainsExplicitDefinitionOfNoPiaLocalTypes != ThreeState.Unknown); return _lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.True; } } private static bool NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(NamespaceSymbol ns) { foreach (Symbol s in ns.GetMembersUnordered()) { switch (s.Kind) { case SymbolKind.Namespace: if (NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes((NamespaceSymbol)s)) { return true; } break; case SymbolKind.NamedType: if (((NamedTypeSymbol)s).IsExplicitDefinitionOfNoPiaLocalType) { return true; } break; } } return false; } public override NamespaceSymbol GlobalNamespace { get { if ((object)_globalNamespace == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var globalNS = new SourceNamespaceSymbol( this, this, DeclaringCompilation.MergedRootDeclaration, diagnostics); if (Interlocked.CompareExchange(ref _globalNamespace, globalNS, null) == null) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _globalNamespace; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartValidatingReferencedAssemblies: { BindingDiagnosticBag diagnostics = null; if (AnyReferencedAssembliesAreLinked) { diagnostics = BindingDiagnosticBag.GetInstance(); ValidateLinkedAssemblies(diagnostics, cancellationToken); } if (_state.NotePartComplete(CompletionPart.StartValidatingReferencedAssemblies)) { if (diagnostics != null) { _assemblySymbol.AddDeclarationDiagnostics(diagnostics); } _state.NotePartComplete(CompletionPart.FinishValidatingReferencedAssemblies); } if (diagnostics != null) { diagnostics.Free(); } } break; case CompletionPart.FinishValidatingReferencedAssemblies: // some other thread has started validating references (otherwise we would be in the case above) so // we just wait for it to both finish and report the diagnostics. Debug.Assert(_state.HasComplete(CompletionPart.StartValidatingReferencedAssemblies)); _state.SpinWaitComplete(CompletionPart.FinishValidatingReferencedAssemblies, cancellationToken); break; case CompletionPart.MembersCompleted: this.GlobalNamespace.ForceComplete(locationOpt, cancellationToken); if (this.GlobalNamespace.HasComplete(CompletionPart.MembersCompleted)) { _state.NotePartComplete(CompletionPart.MembersCompleted); } else { Debug.Assert(locationOpt != null, "If no location was specified, then the namespace members should be completed"); return; } break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(incompletePart); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } private void ValidateLinkedAssemblies(BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { foreach (AssemblySymbol a in GetReferencedAssemblySymbols()) { cancellationToken.ThrowIfCancellationRequested(); if (!a.IsMissing && a.IsLinked) { bool hasGuidAttribute = false; bool hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = false; foreach (var attrData in a.GetAttributes()) { if (attrData.IsTargetAttribute(a, AttributeDescription.GuidAttribute)) { string guidString; if (attrData.TryGetGuidAttributeValue(out guidString)) { hasGuidAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.ImportedFromTypeLibAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.PrimaryInteropAssemblyAttribute)) { if (attrData.CommonConstructorArguments.Length == 2) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } if (hasGuidAttribute && hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { break; } } if (!hasGuidAttribute) { // ERRID_PIAHasNoAssemblyGuid1/ERR_NoPIAAssemblyMissingAttribute diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttribute, NoLocation.Singleton, a, AttributeDescription.GuidAttribute.FullName); } if (!hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { // ERRID_PIAHasNoTypeLibAttribute1/ERR_NoPIAAssemblyMissingAttributes diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttributes, NoLocation.Singleton, a, AttributeDescription.ImportedFromTypeLibAttribute.FullName, AttributeDescription.PrimaryInteropAssemblyAttribute.FullName); } } } } public override ImmutableArray<Location> Locations { get { if (_locations.IsDefault) { ImmutableInterlocked.InterlockedInitialize( ref _locations, DeclaringCompilation.MergedRootDeclaration.Declarations.SelectAsArray(d => (Location)d.Location)); } return _locations; } } /// <summary> /// The name (contains extension) /// </summary> private readonly string _name; public override string Name { get { return _name; } } public override Symbol ContainingSymbol { get { return _assemblySymbol; } } public override AssemblySymbol ContainingAssembly { get { return _assemblySymbol; } } internal SourceAssemblySymbol ContainingSourceAssembly { get { return _assemblySymbol; } } /// <remarks> /// This override is essential - it's a base case of the recursive definition. /// </remarks> internal override CSharpCompilation DeclaringCompilation { get { return _assemblySymbol.DeclaringCompilation; } } internal override ICollection<string> TypeNames { get { return _sources.TypeNames; } } internal override ICollection<string> NamespaceNames { get { return _sources.NamespaceNames; } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return _assemblySymbol; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Module; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return ContainingAssembly.IsInteractive ? AttributeLocation.None : AttributeLocation.Assembly | AttributeLocation.Module; } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { var mergedAttributes = ((SourceAssemblySymbol)this.ContainingAssembly).GetAttributeDeclarations(); if (LoadAndValidateAttributes(OneOrMany.Create(mergedAttributes), ref _lazyCustomAttributesBag)) { var completed = _state.NotePartComplete(CompletionPart.Attributes); Debug.Assert(completed); } } return _lazyCustomAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private ModuleWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ModuleWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultCharSetAttribute)) { CharSet charSet = attribute.GetConstructorArgument<CharSet>(0, SpecialType.System_Enum); if (!ModuleWellKnownAttributeData.IsValidCharSet(charSet)) { CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); } else { arguments.GetOrCreateData<ModuleWellKnownAttributeData>().DefaultCharacterSet = charSet; } } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.NullableContextAttribute | ReservedAttributes.NullablePublicOnlyAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) { CSharpAttributeData.DecodeSkipLocalsInitAttribute<ModuleWellKnownAttributeData>(DeclaringCompilation, ref arguments); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = _assemblySymbol.DeclaringCompilation; if (compilation.Options.AllowUnsafe) { // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known type isn't available. if (!(compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute) is MissingMetadataTypeSymbol)) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Security_UnverifiableCodeAttribute__ctor)); } } if (moduleBuilder.ShouldEmitNullablePublicOnlyAttribute()) { var includesInternals = ImmutableArray.Create( new TypedConstant(compilation.GetSpecialType(SpecialType.System_Boolean), TypedConstantKind.Primitive, _assemblySymbol.InternalsAreVisible)); AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullablePublicOnlyAttribute(includesInternals)); } } internal override bool HasAssemblyCompilationRelaxationsAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasCompilationRelaxationsAttribute; } } internal override bool HasAssemblyRuntimeCompatibilityAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasRuntimeCompatibilityAttribute; } } internal override CharSet? DefaultMarshallingCharSet { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasDefaultCharSetAttribute ? data.DefaultCharacterSet : (CharSet?)null; } } public sealed override bool AreLocalsZeroed { get { var data = GetDecodedWellKnownAttributeData(); return data?.HasSkipLocalsInitAttribute != true; } } public override ModuleMetadata GetMetadata() => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents the primary module of an assembly being built by compiler. /// </summary> internal sealed class SourceModuleSymbol : NonMissingModuleSymbol, IAttributeTargetSymbol { /// <summary> /// Owning assembly. /// </summary> private readonly SourceAssemblySymbol _assemblySymbol; private ImmutableArray<AssemblySymbol> _lazyAssembliesToEmbedTypesFrom; private ThreeState _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = ThreeState.Unknown; /// <summary> /// The declarations corresponding to the source files of this module. /// </summary> private readonly DeclarationTable _sources; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private ImmutableArray<Location> _locations; private NamespaceSymbol _globalNamespace; private bool _hasBadAttributes; internal SourceModuleSymbol( SourceAssemblySymbol assemblySymbol, DeclarationTable declarations, string moduleName) { Debug.Assert((object)assemblySymbol != null); _assemblySymbol = assemblySymbol; _sources = declarations; _name = moduleName; } internal void RecordPresenceOfBadAttributes() { _hasBadAttributes = true; } internal bool HasBadAttributes { get { return _hasBadAttributes; } } internal override int Ordinal { get { return 0; } } internal override Machine Machine { get { switch (DeclaringCompilation.Options.Platform) { case Platform.Arm: return Machine.ArmThumb2; case Platform.X64: return Machine.Amd64; case Platform.Arm64: return Machine.Arm64; case Platform.Itanium: return Machine.IA64; default: return Machine.I386; } } } internal override bool Bit32Required { get { return DeclaringCompilation.Options.Platform == Platform.X86; } } internal bool AnyReferencedAssembliesAreLinked { get { return GetAssembliesToEmbedTypesFrom().Length > 0; } } internal bool MightContainNoPiaLocalTypes() { return AnyReferencedAssembliesAreLinked || ContainsExplicitDefinitionOfNoPiaLocalTypes; } internal ImmutableArray<AssemblySymbol> GetAssembliesToEmbedTypesFrom() { if (_lazyAssembliesToEmbedTypesFrom.IsDefault) { AssertReferencesInitialized(); var buffer = ArrayBuilder<AssemblySymbol>.GetInstance(); foreach (AssemblySymbol asm in this.GetReferencedAssemblySymbols()) { if (asm.IsLinked) { buffer.Add(asm); } } ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssembliesToEmbedTypesFrom, buffer.ToImmutableAndFree(), default(ImmutableArray<AssemblySymbol>)); } Debug.Assert(!_lazyAssembliesToEmbedTypesFrom.IsDefault); return _lazyAssembliesToEmbedTypesFrom; } internal bool ContainsExplicitDefinitionOfNoPiaLocalTypes { get { if (_lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.Unknown) { _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(GlobalNamespace).ToThreeState(); } Debug.Assert(_lazyContainsExplicitDefinitionOfNoPiaLocalTypes != ThreeState.Unknown); return _lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.True; } } private static bool NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(NamespaceSymbol ns) { foreach (Symbol s in ns.GetMembersUnordered()) { switch (s.Kind) { case SymbolKind.Namespace: if (NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes((NamespaceSymbol)s)) { return true; } break; case SymbolKind.NamedType: if (((NamedTypeSymbol)s).IsExplicitDefinitionOfNoPiaLocalType) { return true; } break; } } return false; } public override NamespaceSymbol GlobalNamespace { get { if ((object)_globalNamespace == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var globalNS = new SourceNamespaceSymbol( this, this, DeclaringCompilation.MergedRootDeclaration, diagnostics); if (Interlocked.CompareExchange(ref _globalNamespace, globalNS, null) == null) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _globalNamespace; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartValidatingReferencedAssemblies: { BindingDiagnosticBag diagnostics = null; if (AnyReferencedAssembliesAreLinked) { diagnostics = BindingDiagnosticBag.GetInstance(); ValidateLinkedAssemblies(diagnostics, cancellationToken); } if (_state.NotePartComplete(CompletionPart.StartValidatingReferencedAssemblies)) { if (diagnostics != null) { _assemblySymbol.AddDeclarationDiagnostics(diagnostics); } _state.NotePartComplete(CompletionPart.FinishValidatingReferencedAssemblies); } if (diagnostics != null) { diagnostics.Free(); } } break; case CompletionPart.FinishValidatingReferencedAssemblies: // some other thread has started validating references (otherwise we would be in the case above) so // we just wait for it to both finish and report the diagnostics. Debug.Assert(_state.HasComplete(CompletionPart.StartValidatingReferencedAssemblies)); _state.SpinWaitComplete(CompletionPart.FinishValidatingReferencedAssemblies, cancellationToken); break; case CompletionPart.MembersCompleted: this.GlobalNamespace.ForceComplete(locationOpt, cancellationToken); if (this.GlobalNamespace.HasComplete(CompletionPart.MembersCompleted)) { _state.NotePartComplete(CompletionPart.MembersCompleted); } else { Debug.Assert(locationOpt != null, "If no location was specified, then the namespace members should be completed"); return; } break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(incompletePart); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } private void ValidateLinkedAssemblies(BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { foreach (AssemblySymbol a in GetReferencedAssemblySymbols()) { cancellationToken.ThrowIfCancellationRequested(); if (!a.IsMissing && a.IsLinked) { bool hasGuidAttribute = false; bool hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = false; foreach (var attrData in a.GetAttributes()) { if (attrData.IsTargetAttribute(a, AttributeDescription.GuidAttribute)) { string guidString; if (attrData.TryGetGuidAttributeValue(out guidString)) { hasGuidAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.ImportedFromTypeLibAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.PrimaryInteropAssemblyAttribute)) { if (attrData.CommonConstructorArguments.Length == 2) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } if (hasGuidAttribute && hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { break; } } if (!hasGuidAttribute) { // ERRID_PIAHasNoAssemblyGuid1/ERR_NoPIAAssemblyMissingAttribute diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttribute, NoLocation.Singleton, a, AttributeDescription.GuidAttribute.FullName); } if (!hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { // ERRID_PIAHasNoTypeLibAttribute1/ERR_NoPIAAssemblyMissingAttributes diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttributes, NoLocation.Singleton, a, AttributeDescription.ImportedFromTypeLibAttribute.FullName, AttributeDescription.PrimaryInteropAssemblyAttribute.FullName); } } } } public override ImmutableArray<Location> Locations { get { if (_locations.IsDefault) { ImmutableInterlocked.InterlockedInitialize( ref _locations, DeclaringCompilation.MergedRootDeclaration.Declarations.SelectAsArray(d => (Location)d.Location)); } return _locations; } } /// <summary> /// The name (contains extension) /// </summary> private readonly string _name; public override string Name { get { return _name; } } public override Symbol ContainingSymbol { get { return _assemblySymbol; } } public override AssemblySymbol ContainingAssembly { get { return _assemblySymbol; } } internal SourceAssemblySymbol ContainingSourceAssembly { get { return _assemblySymbol; } } /// <remarks> /// This override is essential - it's a base case of the recursive definition. /// </remarks> internal override CSharpCompilation DeclaringCompilation { get { return _assemblySymbol.DeclaringCompilation; } } internal override ICollection<string> TypeNames { get { return _sources.TypeNames; } } internal override ICollection<string> NamespaceNames { get { return _sources.NamespaceNames; } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return _assemblySymbol; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Module; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return ContainingAssembly.IsInteractive ? AttributeLocation.None : AttributeLocation.Assembly | AttributeLocation.Module; } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { var mergedAttributes = ((SourceAssemblySymbol)this.ContainingAssembly).GetAttributeDeclarations(); if (LoadAndValidateAttributes(OneOrMany.Create(mergedAttributes), ref _lazyCustomAttributesBag)) { var completed = _state.NotePartComplete(CompletionPart.Attributes); Debug.Assert(completed); } } return _lazyCustomAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private ModuleWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ModuleWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultCharSetAttribute)) { CharSet charSet = attribute.GetConstructorArgument<CharSet>(0, SpecialType.System_Enum); if (!ModuleWellKnownAttributeData.IsValidCharSet(charSet)) { CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); } else { arguments.GetOrCreateData<ModuleWellKnownAttributeData>().DefaultCharacterSet = charSet; } } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.NullableContextAttribute | ReservedAttributes.NullablePublicOnlyAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) { CSharpAttributeData.DecodeSkipLocalsInitAttribute<ModuleWellKnownAttributeData>(DeclaringCompilation, ref arguments); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = _assemblySymbol.DeclaringCompilation; if (compilation.Options.AllowUnsafe) { // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known type isn't available. if (!(compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute) is MissingMetadataTypeSymbol)) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Security_UnverifiableCodeAttribute__ctor)); } } if (moduleBuilder.ShouldEmitNullablePublicOnlyAttribute()) { var includesInternals = ImmutableArray.Create( new TypedConstant(compilation.GetSpecialType(SpecialType.System_Boolean), TypedConstantKind.Primitive, _assemblySymbol.InternalsAreVisible)); AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullablePublicOnlyAttribute(includesInternals)); } } internal override bool HasAssemblyCompilationRelaxationsAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasCompilationRelaxationsAttribute; } } internal override bool HasAssemblyRuntimeCompatibilityAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasRuntimeCompatibilityAttribute; } } internal override CharSet? DefaultMarshallingCharSet { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasDefaultCharSetAttribute ? data.DefaultCharacterSet : (CharSet?)null; } } public sealed override bool AreLocalsZeroed { get { var data = GetDecodedWellKnownAttributeData(); return data?.HasSkipLocalsInitAttribute != true; } } public override ModuleMetadata GetMetadata() => null; } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); return isVar ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "unmanaged" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="keyword"> /// Set to <see cref="ConstraintContextualKeyword.None"/> if syntax binds to a type in the current context, otherwise /// syntax binds to the corresponding keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to a contextual constraint keyword. /// </returns> private TypeWithAnnotations BindTypeOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { var symbol = BindTypeOrAliasOrConstraintKeyword(syntax, diagnostics, out keyword); Debug.Assert((keyword != ConstraintContextualKeyword.None) == symbol.IsDefault); return (keyword != ConstraintContextualKeyword.None) ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <param name="alias">Alias symbol if syntax binds to an alias.</param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar, out AliasSymbol alias) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); if (isVar) { alias = null; return default; } else { return UnwrapAlias(symbol, out alias, diagnostics, syntax).TypeWithAnnotations; } } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type or alias to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type or alias if syntax binds to a type or alias to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { if (syntax.IsVar) { var symbol = BindTypeOrAliasOrKeyword((IdentifierNameSyntax)syntax, diagnostics, out isVar); if (isVar) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImplicitLocal, diagnostics); } return symbol; } else { isVar = false; return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } private enum ConstraintContextualKeyword { None, Unmanaged, NotNull, } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { if (syntax.IsUnmanaged) { keyword = ConstraintContextualKeyword.Unmanaged; } else if (syntax.IsNotNull) { keyword = ConstraintContextualKeyword.NotNull; } else { keyword = ConstraintContextualKeyword.None; } if (keyword != ConstraintContextualKeyword.None) { var identifierSyntax = (IdentifierNameSyntax)syntax; var symbol = BindTypeOrAliasOrKeyword(identifierSyntax, diagnostics, out bool isKeyword); if (isKeyword) { switch (keyword) { case ConstraintContextualKeyword.Unmanaged: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureUnmanagedGenericTypeConstraint, diagnostics); break; case ConstraintContextualKeyword.NotNull: CheckFeatureAvailability(identifierSyntax, MessageID.IDS_FeatureNotNullGenericTypeConstraint, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(keyword); } } else { keyword = ConstraintContextualKeyword.None; } return symbol; } else { return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } /// <summary> /// Binds the type for the syntax taking into account possibility of the type being a keyword. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// PREREQUISITE: syntax should be checked to match the keyword, like <see cref="TypeSyntax.IsVar"/> or <see cref="TypeSyntax.IsUnmanaged"/>. /// Otherwise, call <see cref="Binder.BindTypeOrAlias(ExpressionSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> instead. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(IdentifierNameSyntax syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { return BindTypeOrAliasOrKeyword(((IdentifierNameSyntax)syntax).Identifier, syntax, diagnostics, out isKeyword); } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(SyntaxToken identifier, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { // Keywords can only be IdentifierNameSyntax var identifierValueText = identifier.ValueText; Symbol symbol = null; // Perform name lookup without generating diagnostics as it could possibly be a keyword in the current context. var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsInternal(lookupResult, identifierValueText, arity: 0, useSiteInfo: ref discardedUseSiteInfo, basesBeingResolved: null, options: LookupOptions.NamespacesOrTypesOnly, diagnose: false); // We have following possible cases for lookup: // 1) LookupResultKind.Empty: must be a keyword // 2) LookupResultKind.Viable: // a) Single viable result that corresponds to 1) a non-error type: cannot be a keyword // 2) an error type: must be a keyword // b) Single viable result that corresponds to namespace: must be a keyword // c) Multi viable result (ambiguous result), we must return an error type: cannot be a keyword // 3) Non viable, non empty lookup result: must be a keyword // BREAKING CHANGE: Case (2)(c) is a breaking change from the native compiler. // BREAKING CHANGE: Native compiler interprets lookup with ambiguous result to correspond to bind // BREAKING CHANGE: to "var" keyword (isVar = true), rather than reporting an error. // BREAKING CHANGE: See test SemanticErrorTests.ErrorMeansSuccess_var() for an example. switch (lookupResult.Kind) { case LookupResultKind.Empty: // Case (1) isKeyword = true; symbol = null; break; case LookupResultKind.Viable: // Case (2) var resultDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); bool wasError; symbol = ResultSymbol( lookupResult, identifierValueText, arity: 0, where: syntax, diagnostics: resultDiagnostics, suppressUseSiteDiagnostics: false, wasError: out wasError, qualifierOpt: null); // Here, we're mimicking behavior of dev10. If the identifier fails to bind // as a type, even if the reason is (e.g.) a type/alias conflict, then treat // it as the contextual keyword. if (wasError && lookupResult.IsSingleViable) { // NOTE: don't report diagnostics - we're not going to use the lookup result. resultDiagnostics.DiagnosticBag.Free(); // Case (2)(a)(2) goto default; } diagnostics.AddRange(resultDiagnostics.DiagnosticBag); resultDiagnostics.DiagnosticBag.Free(); if (lookupResult.IsSingleViable) { var type = UnwrapAlias(symbol, diagnostics, syntax) as TypeSymbol; if ((object)type != null) { // Case (2)(a)(1) isKeyword = false; } else { // Case (2)(b) Debug.Assert(UnwrapAliasNoDiagnostics(symbol) is NamespaceSymbol); isKeyword = true; symbol = null; } } else { // Case (2)(c) isKeyword = false; } break; default: // Case (3) isKeyword = true; symbol = null; break; } lookupResult.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(identifier), symbol); } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it unwraps the alias // and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); return UnwrapAlias(symbol, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it stores the AliasSymbol in // the alias parameter, unwraps the alias and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, out AliasSymbol alias, ConsList<TypeSymbol> basesBeingResolved = null) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved); return UnwrapAlias(symbol, out alias, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type or an Alias to Type // and returns the resultant symbol. // NOTE: This method doesn't unwrap aliases. internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAlias(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { Debug.Assert(diagnostics != null); var symbol = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null || suppressUseSiteDiagnostics); // symbol must be a TypeSymbol or an Alias to a TypeSymbol if (symbol.IsType || (symbol.IsAlias && UnwrapAliasNoDiagnostics(symbol.Symbol, basesBeingResolved) is TypeSymbol)) { if (symbol.IsType) { // Obsolete alias targets are reported in UnwrapAlias, but if it was a type (not an // alias to a type) we report the obsolete type here. symbol.TypeWithAnnotations.ReportDiagnosticsIfObsolete(this, syntax, diagnostics); } return symbol; } var diagnosticInfo = diagnostics.Add(ErrorCode.ERR_BadSKknown, syntax.Location, syntax, symbol.Symbol.GetKindText(), MessageID.IDS_SK_TYPE.Localize()); return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbol.Symbol), symbol.Symbol, LookupResultKind.NotATypeOrNamespace, diagnosticInfo)); } /// <summary> /// The immediately containing namespace or named type, or the global /// namespace if containing symbol is neither a namespace or named type. /// </summary> private NamespaceOrTypeSymbol GetContainingNamespaceOrType(Symbol symbol) { return symbol.ContainingNamespaceOrType() ?? this.Compilation.Assembly.GlobalNamespace; } internal Symbol BindNamespaceAliasSymbol(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (node.Identifier.Kind() == SyntaxKind.GlobalKeyword) { return this.Compilation.GlobalNamespaceAlias; } else { bool wasError; var plainName = node.Identifier.ValueText; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, plainName, 0, ref useSiteInfo, null, LookupOptions.NamespaceAliasesOnly); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = ResultSymbol(result, plainName, 0, node, diagnostics, false, out wasError, qualifierOpt: null, options: LookupOptions.NamespaceAliasesOnly); result.Free(); return bindingResult; } } internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { return BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null); } /// <summary> /// This method is used in deeply recursive parts of the compiler and requires a non-trivial amount of stack /// space to execute. Preventing inlining here to keep recursive frames small. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var result = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); Debug.Assert(!result.IsDefault); return UnwrapAlias(result, diagnostics, syntax, basesBeingResolved); } #nullable enable /// <summary> /// Bind the syntax into a namespace, type or alias symbol. /// </summary> /// <remarks> /// This method is used in deeply recursive parts of the compiler. Specifically this and /// <see cref="BindQualifiedName(ExpressionSyntax, SimpleNameSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> /// are mutually recursive. The non-recursive parts of this method tend to reserve significantly large /// stack frames due to their use of large struct like <see cref="TypeWithAnnotations"/>. /// /// To keep the stack frame size on recursive paths small the non-recursive parts are factored into local /// functions. This means we pay their stack penalty only when they are used. They are themselves big /// enough they should be disqualified from inlining. In the future when attributes are allowed on /// local functions we should explicitly mark them as <see cref="MethodImplOptions.NoInlining"/> /// </remarks> internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeOrAliasSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { switch (syntax.Kind()) { case SyntaxKind.NullableType: return bindNullable(); case SyntaxKind.PredefinedType: return bindPredefined(); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt: null); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt: null); case SyntaxKind.AliasQualifiedName: return bindAlias(); case SyntaxKind.QualifiedName: { var node = (QualifiedNameSyntax)syntax; return BindQualifiedName(node.Left, node.Right, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.SimpleMemberAccessExpression: { var node = (MemberAccessExpressionSyntax)syntax; return BindQualifiedName(node.Expression, node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.ArrayType: { return BindArrayType((ArrayTypeSyntax)syntax, diagnostics, permitDimensions: false, basesBeingResolved, disallowRestrictedTypes: true); } case SyntaxKind.PointerType: return bindPointer(); case SyntaxKind.FunctionPointerType: var functionPointerTypeSyntax = (FunctionPointerTypeSyntax)syntax; if (GetUnsafeDiagnosticInfo(sizeOfTypeOpt: null) is CSDiagnosticInfo info) { var @delegate = functionPointerTypeSyntax.DelegateKeyword; var asterisk = functionPointerTypeSyntax.AsteriskToken; RoslynDebug.Assert(@delegate.SyntaxTree is object); diagnostics.Add(info, Location.Create(@delegate.SyntaxTree, TextSpan.FromBounds(@delegate.SpanStart, asterisk.Span.End))); } return TypeWithAnnotations.Create( FunctionPointerTypeSymbol.CreateFromSource( functionPointerTypeSyntax, this, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics)); case SyntaxKind.OmittedTypeArgument: { return BindTypeArgument((TypeSyntax)syntax, diagnostics, basesBeingResolved); } case SyntaxKind.TupleType: { var tupleTypeSyntax = (TupleTypeSyntax)syntax; return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(tupleTypeSyntax.CloseParenToken), BindTupleType(tupleTypeSyntax, diagnostics, basesBeingResolved)); } case SyntaxKind.RefType: { // ref needs to be handled by the caller var refTypeSyntax = (RefTypeSyntax)syntax; var refToken = refTypeSyntax.RefKeyword; if (!syntax.HasErrors) { diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refToken.GetLocation(), refToken.ToString()); } return BindNamespaceOrTypeOrAliasSymbol(refTypeSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } default: { // This is invalid syntax for a type. This arises when a constant pattern that fails to bind // is attempted to be bound as a type pattern. return createErrorType(); } } void reportNullableReferenceTypesIfNeeded(SyntaxToken questionToken, TypeWithAnnotations typeArgument = default) { bool isNullableEnabled = AreNullableAnnotationsEnabled(questionToken); bool isGeneratedCode = IsGeneratedCode(questionToken); var location = questionToken.GetLocation(); if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { // Inside a method body or other executable code, we can question IsValueType without causing cycles. if (typeArgument.HasType && !ShouldCheckConstraints) { LazyMissingNonNullTypesContextDiagnosticInfo.AddAll( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } else { LazyMissingNonNullTypesContextDiagnosticInfo.ReportNullableReferenceTypesIfNeeded( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } } } NamespaceOrTypeOrAliasSymbolWithAnnotations bindNullable() { var nullableSyntax = (NullableTypeSyntax)syntax; TypeSyntax typeArgumentSyntax = nullableSyntax.ElementType; TypeWithAnnotations typeArgument = BindType(typeArgumentSyntax, diagnostics, basesBeingResolved); TypeWithAnnotations constructedType = typeArgument.SetIsAnnotated(Compilation); reportNullableReferenceTypesIfNeeded(nullableSyntax.QuestionToken, typeArgument); if (!ShouldCheckConstraints) { diagnostics.Add(new LazyUseSiteDiagnosticsInfoForNullableType(Compilation.LanguageVersion, constructedType), syntax.GetLocation()); } else if (constructedType.IsNullableType()) { ReportUseSite(constructedType.Type.OriginalDefinition, diagnostics, syntax); var type = (NamedTypeSymbol)constructedType.Type; var location = syntax.Location; type.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: true, location, diagnostics)); } else if (GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(Compilation.LanguageVersion, constructedType) is { } diagnosticInfo) { diagnostics.Add(diagnosticInfo, syntax.Location); } return constructedType; } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPredefined() { var predefinedType = (PredefinedTypeSyntax)syntax; var type = BindPredefinedTypeSymbol(predefinedType, diagnostics); return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(predefinedType.Keyword), type); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindAlias() { var node = (AliasQualifiedNameSyntax)syntax; var bindingResult = BindNamespaceAliasSymbol(node.Alias, diagnostics); var alias = bindingResult as AliasSymbol; NamespaceOrTypeSymbol left = (alias is object) ? alias.Target : (NamespaceOrTypeSymbol)bindingResult; if (left.Kind == SymbolKind.NamedType) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(left, LookupResultKind.NotATypeOrNamespace, diagnostics.Add(ErrorCode.ERR_ColColWithTypeAlias, node.Alias.Location, node.Alias.Identifier.Text))); } return this.BindSimpleNamespaceOrTypeOrAliasSymbol(node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPointer() { var node = (PointerTypeSyntax)syntax; var elementType = BindType(node.ElementType, diagnostics, basesBeingResolved); ReportUnsafeIfNotAllowed(node, diagnostics); if (!Flags.HasFlag(BinderFlags.SuppressConstraintChecks)) { CheckManagedAddr(Compilation, elementType.Type, node.Location, diagnostics); } return TypeWithAnnotations.Create(new PointerTypeSymbol(elementType)); } NamespaceOrTypeOrAliasSymbolWithAnnotations createErrorType() { diagnostics.Add(ErrorCode.ERR_TypeExpected, syntax.GetLocation()); return TypeWithAnnotations.Create(CreateErrorType()); } } internal static CSDiagnosticInfo? GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(LanguageVersion languageVersion, in TypeWithAnnotations type) { if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8()) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); if (requiredVersion > languageVersion) { return new CSDiagnosticInfo(ErrorCode.ERR_NullableUnconstrainedTypeParameter, new CSharpRequiredLanguageVersion(requiredVersion)); } } return null; } #nullable disable private TypeWithAnnotations BindArrayType( ArrayTypeSyntax node, BindingDiagnosticBag diagnostics, bool permitDimensions, ConsList<TypeSymbol> basesBeingResolved, bool disallowRestrictedTypes) { TypeWithAnnotations type = BindType(node.ElementType, diagnostics, basesBeingResolved); if (type.IsStatic) { // CS0719: '{0}': array elements cannot be of static type Error(diagnostics, ErrorCode.ERR_ArrayOfStaticClass, node.ElementType, type.Type); } if (disallowRestrictedTypes) { // Restricted types cannot be on the heap, but they can be on the stack, so are allowed in a stackalloc if (ShouldCheckConstraints) { if (type.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node.ElementType, type.Type); } } else { diagnostics.Add(new LazyArrayElementCantBeRefAnyDiagnosticInfo(type), node.ElementType.GetLocation()); } } for (int i = node.RankSpecifiers.Count - 1; i >= 0; i--) { var rankSpecifier = node.RankSpecifiers[i]; var dimension = rankSpecifier.Sizes; if (!permitDimensions && dimension.Count != 0 && dimension[0].Kind() != SyntaxKind.OmittedArraySizeExpression) { // https://github.com/dotnet/roslyn/issues/32464 // Should capture invalid dimensions for use in `SemanticModel` and `IOperation`. Error(diagnostics, ErrorCode.ERR_ArraySizeInDeclaration, rankSpecifier); } var array = ArrayTypeSymbol.CreateCSharpArray(this.Compilation.Assembly, type, rankSpecifier.Rank); type = TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(rankSpecifier.CloseBracketToken), array); } return type; } private TypeSymbol BindTupleType(TupleTypeSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved) { int numElements = syntax.Elements.Count; var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(numElements); var locations = ArrayBuilder<Location>.GetInstance(numElements); ArrayBuilder<string> elementNames = null; // set of names already used var uniqueFieldNames = PooledHashSet<string>.GetInstance(); bool hasExplicitNames = false; for (int i = 0; i < numElements; i++) { var argumentSyntax = syntax.Elements[i]; var argumentType = BindType(argumentSyntax.Type, diagnostics, basesBeingResolved); types.Add(argumentType); string name = null; SyntaxToken nameToken = argumentSyntax.Identifier; if (nameToken.Kind() == SyntaxKind.IdentifierToken) { name = nameToken.ValueText; // validate name if we have one hasExplicitNames = true; CheckTupleMemberName(name, i, nameToken, diagnostics, uniqueFieldNames); locations.Add(nameToken.GetLocation()); } else { locations.Add(argumentSyntax.Location); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); } uniqueFieldNames.Free(); if (hasExplicitNames) { // If the tuple type with names is bound we must have the TupleElementNamesAttribute to emit // it is typically there though, if we have ValueTuple at all ReportMissingTupleElementNamesAttributesIfNeeded(Compilation, syntax.GetLocation(), diagnostics); } var typesArray = types.ToImmutableAndFree(); var locationsArray = locations.ToImmutableAndFree(); if (typesArray.Length < 2) { throw ExceptionUtilities.UnexpectedValue(typesArray.Length); } bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); return NamedTypeSymbol.CreateTuple(syntax.Location, typesArray, locationsArray, elementNames == null ? default(ImmutableArray<string>) : elementNames.ToImmutableAndFree(), this.Compilation, this.ShouldCheckConstraints, includeNullability: this.ShouldCheckConstraints && includeNullability, errorPositions: default(ImmutableArray<bool>), syntax: syntax, diagnostics: diagnostics); } internal static void ReportMissingTupleElementNamesAttributesIfNeeded(CSharpCompilation compilation, Location location, BindingDiagnosticBag diagnostics) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!compilation.HasTupleNamesAttributes(bag, location)) { var info = new CSDiagnosticInfo(ErrorCode.ERR_TupleElementNamesAttributeMissing, AttributeDescription.TupleElementNamesAttribute.FullName); Error(diagnostics, info, location); } else { diagnostics.AddRange(bag); } bag.Free(); } private static void CollectTupleFieldMemberName(string name, int elementIndex, int tupleSize, ref ArrayBuilder<string> elementNames) { // add the name to the list // names would typically all be there or none at all // but in case we need to handle this in error cases if (elementNames != null) { elementNames.Add(name); } else { if (name != null) { elementNames = ArrayBuilder<string>.GetInstance(tupleSize); for (int j = 0; j < elementIndex; j++) { elementNames.Add(null); } elementNames.Add(name); } } } private static bool CheckTupleMemberName(string name, int index, SyntaxNodeOrToken syntax, BindingDiagnosticBag diagnostics, PooledHashSet<string> uniqueFieldNames) { int reserved = NamedTypeSymbol.IsTupleElementNameReserved(name); if (reserved == 0) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementNameAnyPosition, syntax, name); return false; } else if (reserved > 0 && reserved != index + 1) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementName, syntax, name, reserved); return false; } else if (!uniqueFieldNames.Add(name)) { Error(diagnostics, ErrorCode.ERR_TupleDuplicateElementName, syntax); return false; } return true; } private NamedTypeSymbol BindPredefinedTypeSymbol(PredefinedTypeSyntax node, BindingDiagnosticBag diagnostics) { return GetSpecialType(node.Keyword.Kind().GetSpecialType(), diagnostics, node); } /// <summary> /// Binds a simple name or the simple name portion of a qualified name. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindSimpleNamespaceOrTypeOrAliasSymbol( SimpleNameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt = null) { // Note that the comment above is a small lie; there is no such thing as the "simple name portion" of // a qualified alias member expression. A qualified alias member expression has the form // "identifier :: identifier optional-type-arguments" -- the right hand side of which // happens to match the syntactic form of a simple name. As a convenience, we analyze the // right hand side of the "::" here because it is so similar to a simple name; the left hand // side is in qualifierOpt. switch (syntax.Kind()) { default: return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(qualifierOpt ?? this.Compilation.Assembly.GlobalNamespace, string.Empty, arity: 0, errorInfo: null)); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt); } } private static bool IsViableType(LookupResult result) { if (!result.IsMultiViable) { return false; } foreach (var s in result.Symbols) { switch (s.Kind) { case SymbolKind.Alias: if (((AliasSymbol)s).Target.Kind == SymbolKind.NamedType) return true; break; case SymbolKind.NamedType: case SymbolKind.TypeParameter: return true; } } return false; } protected NamespaceOrTypeOrAliasSymbolWithAnnotations BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol( IdentifierNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt) { var identifierValueText = node.Identifier.ValueText; // If we are here in an error-recovery scenario, say, "goo<int, >(123);" then // we might have an 'empty' simple name. In that case do not report an // 'unable to find ""' error; we've already reported an error in the parser so // just bail out with an error symbol. if (string.IsNullOrWhiteSpace(identifierValueText)) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol( Compilation.Assembly.GlobalNamespace, identifierValueText, 0, new CSDiagnosticInfo(ErrorCode.ERR_SingleTypeNameNotFound))); } var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, identifierValueText, 0, diagnostics); if ((object)errorResult != null) { return TypeWithAnnotations.Create(errorResult); } var result = LookupResult.GetInstance(); LookupOptions options = GetSimpleNameLookupOptions(node, node.Identifier.IsVerbatimIdentifier()); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(result, qualifierOpt, identifierValueText, 0, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = null; // If we were looking up "dynamic" or "nint" at the topmost level and didn't find anything good, // use that particular type (assuming the /langversion is supported). if ((object)qualifierOpt == null && !IsViableType(result)) { if (node.Identifier.ValueText == "dynamic") { if ((node.Parent == null || node.Parent.Kind() != SyntaxKind.Attribute && // dynamic not allowed as attribute type SyntaxFacts.IsInTypeOnlyContext(node)) && Compilation.LanguageVersion >= MessageID.IDS_FeatureDynamic.RequiredVersion()) { bindingResult = Compilation.DynamicType; ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } else { bindingResult = BindNativeIntegerSymbolIfAny(node, diagnostics); } } if (bindingResult is null) { bool wasError; bindingResult = ResultSymbol(result, identifierValueText, 0, node, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (bindingResult.Kind == SymbolKind.Alias) { var aliasTarget = ((AliasSymbol)bindingResult).GetAliasTarget(basesBeingResolved); if (aliasTarget.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)aliasTarget).ContainsDynamic()) { ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } } result.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(node.Identifier), bindingResult); } /// <summary> /// If the node is "nint" or "nuint" and not alone inside nameof, return the corresponding native integer symbol. /// Otherwise return null. /// </summary> private NamedTypeSymbol BindNativeIntegerSymbolIfAny(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { SpecialType specialType; switch (node.Identifier.Text) { case "nint": specialType = SpecialType.System_IntPtr; break; case "nuint": specialType = SpecialType.System_UIntPtr; break; default: return null; } switch (node.Parent) { case AttributeSyntax parent when parent.Name == node: // [nint] return null; case UsingDirectiveSyntax parent when parent.Name == node: // using nint; using A = nuint; return null; case ArgumentSyntax parent when // nameof(nint) (IsInsideNameof && parent.Parent?.Parent is InvocationExpressionSyntax invocation && (invocation.Expression as IdentifierNameSyntax)?.Identifier.ContextualKind() == SyntaxKind.NameOfKeyword): // Don't bind nameof(nint) or nameof(nuint) so that ERR_NameNotInContext is reported. return null; } CheckFeatureAvailability(node, MessageID.IDS_FeatureNativeInt, diagnostics); return this.GetSpecialType(specialType, diagnostics, node).AsNativeInteger(); } private void ReportUseSiteDiagnosticForDynamic(BindingDiagnosticBag diagnostics, IdentifierNameSyntax node) { // Dynamic type might be bound in a declaration context where we need to synthesize the DynamicAttribute. // Here we report the use site error (ERR_DynamicAttributeMissing) for missing DynamicAttribute type or it's constructors. // // BREAKING CHANGE: Native compiler reports ERR_DynamicAttributeMissing at emit time when synthesizing DynamicAttribute. // Currently, in Roslyn we don't support reporting diagnostics while synthesizing attributes, these diagnostics are reported at bind time. // Hence, we report this diagnostic here. Note that DynamicAttribute has two constructors, and either of them may be used while // synthesizing the DynamicAttribute (see DynamicAttributeEncoder.Encode method for details). // However, unlike the native compiler which reports use site diagnostic only for the specific DynamicAttribute constructor which is going to be used, // we report it for both the constructors and also for boolean type (used by the second constructor). // This is a breaking change for the case where only one of the two constructor of DynamicAttribute is missing, but we never use it for any of the synthesized DynamicAttributes. // However, this seems like a very unlikely scenario and an acceptable break. if (node.IsTypeInContextWhichNeedsDynamicAttribute()) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!Compilation.HasDynamicEmitAttributes(bag, node.Location)) { // CONSIDER: Native compiler reports error CS1980 for each syntax node which binds to dynamic type, we do the same by reporting a diagnostic here. // However, this means we generate multiple duplicate diagnostics, when a single one would suffice. // We may want to consider adding an "Unreported" flag to the DynamicTypeSymbol to suppress duplicate CS1980. // CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference? var info = new CSDiagnosticInfo(ErrorCode.ERR_DynamicAttributeMissing, AttributeDescription.DynamicAttribute.FullName); Symbol.ReportUseSiteDiagnostic(info, diagnostics, node.Location); } else { diagnostics.AddRange(bag); } bag.Free(); this.GetSpecialType(SpecialType.System_Boolean, diagnostics, node); } } // Gets the name lookup options for simple generic or non-generic name. private static LookupOptions GetSimpleNameLookupOptions(NameSyntax node, bool isVerbatimIdentifier) { if (SyntaxFacts.IsAttributeName(node)) { // SPEC: By convention, attribute classes are named with a suffix of Attribute. // SPEC: An attribute-name of the form type-name may either include or omit this suffix. // SPEC: If an attribute class is found both with and without this suffix, an ambiguity // SPEC: is present, and a compile-time error results. If the attribute-name is spelled // SPEC: such that its right-most identifier is a verbatim identifier (§2.4.2), then only // SPEC: an attribute without a suffix is matched, thus enabling such an ambiguity to be resolved. return isVerbatimIdentifier ? LookupOptions.VerbatimNameAttributeTypeOnly : LookupOptions.AttributeTypeOnly; } else { return LookupOptions.NamespacesOrTypesOnly; } } private static Symbol UnwrapAliasNoDiagnostics(Symbol symbol, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.Kind == SymbolKind.Alias) { return ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { AliasSymbol discarded; return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out discarded, diagnostics, syntax, basesBeingResolved)); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out alias, diagnostics, syntax, basesBeingResolved)); } alias = null; return symbol; } private Symbol UnwrapAlias(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { AliasSymbol discarded; return UnwrapAlias(symbol, out discarded, diagnostics, syntax, basesBeingResolved); } private Symbol UnwrapAlias(Symbol symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(syntax != null); Debug.Assert(diagnostics != null); if (symbol.Kind == SymbolKind.Alias) { alias = (AliasSymbol)symbol; var result = alias.GetAliasTarget(basesBeingResolved); var type = result as TypeSymbol; if ((object)type != null) { // pass args in a value tuple to avoid allocating a closure var args = (this, diagnostics, syntax); type.VisitType((typePart, argTuple, isNested) => { argTuple.Item1.ReportDiagnosticsIfObsolete(argTuple.diagnostics, typePart, argTuple.syntax, hasBaseReceiver: false); return false; }, args); } return result; } alias = null; return symbol; } private TypeWithAnnotations BindGenericSimpleNamespaceOrTypeOrAliasSymbol( GenericNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt) { // We are looking for a namespace, alias or type name and the user has given // us an identifier followed by a type argument list. Therefore they // must expect the result to be a generic type, and not a namespace or alias. // The result of this method will therefore always be a type symbol of the // correct arity, though it might have to be an error type. // We might be asked to bind a generic simple name of the form "T<,,,>", // which is only legal in the context of "typeof(T<,,,>)". If we are given // no type arguments and we are not in such a context, we'll give an error. // If we do have type arguments, then the result of this method will always // be a generic type symbol constructed with the given type arguments. // There are a number of possible error conditions. First, errors involving lookup: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // Second, we could be asked to resolve an unbound type T<,,,> when // not in a context where it is legal to do so. Note that this is // intended an improvement over the analysis performed by the // native compiler; in the native compiler we catch bad uses of unbound // types at parse time, not at semantic analysis time. That means that // we end up giving confusing "unexpected comma" or "expected type" // errors when it would be more informative to the user to simply // tell them that an unbound type is not legal in this position. // // This also means that we can get semantic analysis of the open // type in the IDE even in what would have been a syntax error case // in the native compiler. // // We need a heuristic to deal with the situation where both kinds of errors // are potentially in play: what if someone says "typeof(Bogus<>.Blah<int>)"? // There are two errors there: first, that Bogus is not found, not a type, // or not of the appropriate arity, and second, that it is illegal to make // a partially unbound type. // // The heuristic we will use is that the former kind of error takes priority // over the latter; if the meaning of "Bogus<>" cannot be successfully // determined then there is no point telling the user that in addition, // it is syntactically wrong. Moreover, at this point we do not know what they // mean by the remainder ".Blah<int>" of the expression and so it seems wrong to // deduce more errors from it. var plainName = node.Identifier.ValueText; SeparatedSyntaxList<TypeSyntax> typeArguments = node.TypeArgumentList.Arguments; bool isUnboundTypeExpr = node.IsUnboundGenericName; LookupOptions options = GetSimpleNameLookupOptions(node, isVerbatimIdentifier: false); NamedTypeSymbol unconstructedType = LookupGenericTypeName( diagnostics, basesBeingResolved, qualifierOpt, node, plainName, node.Arity, options); NamedTypeSymbol resultType; if (isUnboundTypeExpr) { if (!IsUnboundTypeAllowed(node)) { // If we already have an error type then skip reporting that the unbound type is illegal. if (!unconstructedType.IsErrorType()) { // error CS7003: Unexpected use of an unbound generic name diagnostics.Add(ErrorCode.ERR_UnexpectedUnboundGenericName, node.Location); } resultType = unconstructedType.Construct( UnboundArgumentErrorTypeSymbol.CreateTypeArguments( unconstructedType.TypeParameters, node.Arity, errorInfo: null), unbound: false); } else { resultType = unconstructedType.AsUnboundGenericType(); } } else if ((Flags & BinderFlags.SuppressTypeArgumentBinding) != 0) { resultType = unconstructedType.Construct(PlaceholderTypeArgumentSymbol.CreateTypeArguments(unconstructedType.TypeParameters)); } else { // It's not an unbound type expression, so we must have type arguments, and we have a // generic type of the correct arity in hand (possibly an error type). Bind the type // arguments and construct the final result. resultType = ConstructNamedType( unconstructedType, node, typeArguments, BindTypeArguments(typeArguments, diagnostics, basesBeingResolved), basesBeingResolved, diagnostics); } if (options.IsAttributeTypeLookup()) { // Generic type cannot be an attribute type. // Parser error has already been reported, just wrap the result type with error type symbol. Debug.Assert(unconstructedType.IsErrorType()); Debug.Assert(resultType.IsErrorType()); resultType = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(resultType), resultType, LookupResultKind.NotAnAttributeType, errorInfo: null); } return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(node.TypeArgumentList.GreaterThanToken), resultType); } private NamedTypeSymbol LookupGenericTypeName( BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt, GenericNameSyntax node, string plainName, int arity, LookupOptions options) { var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, plainName, arity, diagnostics); if ((object)errorResult != null) { return errorResult; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(lookupResult, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool wasError; Symbol lookupResultSymbol = ResultSymbol(lookupResult, plainName, arity, node, diagnostics, (basesBeingResolved != null), out wasError, qualifierOpt, options); // As we said in the method above, there are three cases here: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // In the first two cases we will be given back an error type symbol of the appropriate arity. // In the third case we will be given back the symbol -- say, a local variable symbol. // // In all three cases the appropriate error has already been reported. (That the // type was not found, that the generic type found does not have that arity, that // the non-generic type found cannot be used with a type argument list, or that // the symbol found is not something that takes type arguments. ) // The first thing to do is to make sure that we have some sort of generic type in hand. // (Note that an error type symbol is always a generic type.) NamedTypeSymbol type = lookupResultSymbol as NamedTypeSymbol; if ((object)type == null) { // We did a lookup with a generic arity, filtered to types and namespaces. If // we got back something other than a type, there had better be an error info // for us. Debug.Assert(lookupResult.Error != null); type = new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(lookupResultSymbol), ImmutableArray.Create<Symbol>(lookupResultSymbol), lookupResult.Kind, lookupResult.Error, arity); } lookupResult.Free(); return type; } private ExtendedErrorTypeSymbol CreateErrorIfLookupOnTypeParameter( CSharpSyntaxNode node, NamespaceOrTypeSymbol qualifierOpt, string name, int arity, BindingDiagnosticBag diagnostics) { if (((object)qualifierOpt != null) && (qualifierOpt.Kind == SymbolKind.TypeParameter)) { var diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_LookupInTypeVariable, qualifierOpt); diagnostics.Add(diagnosticInfo, node.Location); return new ExtendedErrorTypeSymbol(this.Compilation, name, arity, diagnosticInfo, unreported: false); } return null; } private ImmutableArray<TypeWithAnnotations> BindTypeArguments(SeparatedSyntaxList<TypeSyntax> typeArguments, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(typeArguments.Count > 0); var args = ArrayBuilder<TypeWithAnnotations>.GetInstance(); foreach (var argSyntax in typeArguments) { args.Add(BindTypeArgument(argSyntax, diagnostics, basesBeingResolved)); } return args.ToImmutableAndFree(); } private TypeWithAnnotations BindTypeArgument(TypeSyntax typeArgument, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { // Unsafe types can never be type arguments, but there's a special error code for that. var binder = this.WithAdditionalFlags(BinderFlags.SuppressUnsafeDiagnostics); var arg = typeArgument.Kind() == SyntaxKind.OmittedTypeArgument ? TypeWithAnnotations.Create(UnboundArgumentErrorTypeSymbol.Instance) : binder.BindType(typeArgument, diagnostics, basesBeingResolved); return arg; } /// <remarks> /// Keep check and error in sync with ConstructBoundMethodGroupAndReportOmittedTypeArguments. /// </remarks> private NamedTypeSymbol ConstructNamedTypeUnlessTypeArgumentOmitted(SyntaxNode typeSyntax, NamedTypeSymbol type, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BindingDiagnosticBag diagnostics) { if (typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, typeSyntax, type, MessageID.IDS_SK_TYPE.Localize(), typeArgumentsSyntax.Count); // If the syntax looks like an unbound generic type, then they probably wanted the definition. // Give an error indicating that the syntax is incorrect and then use the definition. // CONSIDER: we could construct an unbound generic type symbol, but that would probably be confusing // outside a typeof. return type; } else { // we pass an empty basesBeingResolved here because this invocation is not on any possible path of // infinite recursion in binding base clauses. return ConstructNamedType(type, typeSyntax, typeArgumentsSyntax, typeArguments, basesBeingResolved: null, diagnostics: diagnostics); } } /// <remarks> /// Keep check and error in sync with ConstructNamedTypeUnlessTypeArgumentOmitted. /// </remarks> private static BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedTypeArguments( SyntaxNode syntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BoundExpression receiver, string plainName, ArrayBuilder<Symbol> members, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, bool hasErrors, BindingDiagnosticBag diagnostics) { if (!hasErrors && lookupResult.IsMultiViable && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, syntax, plainName, MessageID.IDS_MethodGroup.Localize(), typeArgumentsSyntax.Count); hasErrors = true; } Debug.Assert(members.Count > 0); switch (members[0].Kind) { case SymbolKind.Method: return new BoundMethodGroup( syntax, typeArguments, receiver, plainName, members.SelectAsArray(s_toMethodSymbolFunc), lookupResult, methodGroupFlags, hasErrors); case SymbolKind.Property: return new BoundPropertyGroup( syntax, members.SelectAsArray(s_toPropertySymbolFunc), receiver, lookupResult.Kind, hasErrors); default: throw ExceptionUtilities.UnexpectedValue(members[0].Kind); } } private static readonly Func<Symbol, MethodSymbol> s_toMethodSymbolFunc = s => (MethodSymbol)s; private static readonly Func<Symbol, PropertySymbol> s_toPropertySymbolFunc = s => (PropertySymbol)s; private NamedTypeSymbol ConstructNamedType( NamedTypeSymbol type, SyntaxNode typeSyntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics) { Debug.Assert(!typeArguments.IsEmpty); type = type.Construct(typeArguments); if (ShouldCheckConstraints && ConstraintsHelper.RequiresChecking(type)) { bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); type.CheckConstraintsForNamedType(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability, typeSyntax.Location, diagnostics), typeSyntax, typeArgumentsSyntax, basesBeingResolved); } return type; } /// <summary> /// Check generic type constraints unless the type is used as part of a type or method /// declaration. In those cases, constraints checking is handled by the caller. /// </summary> private bool ShouldCheckConstraints { get { return !this.Flags.Includes(BinderFlags.SuppressConstraintChecks); } } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindQualifiedName( ExpressionSyntax leftName, SimpleNameSyntax rightName, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var left = BindNamespaceOrTypeSymbol(leftName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics: false).NamespaceOrTypeSymbol; ReportDiagnosticsIfObsolete(diagnostics, left, leftName, hasBaseReceiver: false); bool isLeftUnboundGenericType = left.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)left).IsUnboundGenericType; if (isLeftUnboundGenericType) { // If left name bound to an unbound generic type, // we want to perform right name lookup within // left's original named type definition. left = ((NamedTypeSymbol)left).OriginalDefinition; } // since the name is qualified, it cannot result in a using alias symbol, only a type or namespace var right = this.BindSimpleNamespaceOrTypeOrAliasSymbol(rightName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); // If left name bound to an unbound generic type // and right name bound to a generic type, we must // convert right to an unbound generic type. if (isLeftUnboundGenericType) { return convertToUnboundGenericType(); } return right; // This part is moved into a local function to reduce the method's stack frame size NamespaceOrTypeOrAliasSymbolWithAnnotations convertToUnboundGenericType() { var namedTypeRight = right.Symbol as NamedTypeSymbol; if ((object)namedTypeRight != null && namedTypeRight.IsGenericType) { TypeWithAnnotations type = right.TypeWithAnnotations; return type.WithTypeAndModifiers(namedTypeRight.AsUnboundGenericType(), type.CustomModifiers); } return right; } } internal NamedTypeSymbol GetSpecialType(SpecialType typeId, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetSpecialType(this.Compilation, typeId, node, diagnostics); } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, SyntaxNode node, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, node); return typeSymbol; } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, Location location, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the special /// member isn't found. /// </summary> internal Symbol GetSpecialTypeMember(SpecialMember member, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { Symbol memberSymbol; return TryGetSpecialTypeMember(this.Compilation, member, syntax, diagnostics, out memberSymbol) ? memberSymbol : null; } internal static bool TryGetSpecialTypeMember<TSymbol>(CSharpCompilation compilation, SpecialMember specialMember, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out TSymbol symbol) where TSymbol : Symbol { symbol = (TSymbol)compilation.GetSpecialTypeMember(specialMember); if ((object)symbol == null) { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, syntax.Location, descriptor.DeclaringTypeMetadataName, descriptor.Name); return false; } var useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(symbol); if (useSiteInfo.DiagnosticInfo != null) { diagnostics.ReportUseSiteDiagnostic(useSiteInfo.DiagnosticInfo, new SourceLocation(syntax)); } // No need to track assemblies used by special members or types. They are coming from core library, which // doesn't have any dependencies. return true; } private static UseSiteInfo<AssemblySymbol> GetUseSiteInfoForWellKnownMemberOrContainingType(Symbol symbol) { Debug.Assert(symbol.IsDefinition); UseSiteInfo<AssemblySymbol> info = symbol.GetUseSiteInfo(); symbol.MergeUseSiteInfo(ref info, symbol.ContainingType.GetUseSiteInfo()); return info; } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode node) { return diagnostics.ReportUseSite(symbol, node); } internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxToken token) { return diagnostics.ReportUseSite(symbol, token); } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, Location location) { return diagnostics.ReportUseSite(symbol, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(type, diagnostics, node.Location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { return GetWellKnownType(this.Compilation, type, diagnostics, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(compilation, type, diagnostics, node.Location); } internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { NamedTypeSymbol typeSymbol = compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { NamedTypeSymbol typeSymbol = this.Compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); typeSymbol.AddUseSiteInfo(ref useSiteInfo); return typeSymbol; } internal Symbol GetWellKnownTypeMember(WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { return GetWellKnownTypeMember(Compilation, member, diagnostics, location, syntax, isOptional); } /// <summary> /// Retrieves a well-known type member and reports diagnostics. /// </summary> /// <returns>Null if the symbol is missing.</returns> internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { Debug.Assert((syntax != null) ^ (location != null)); UseSiteInfo<AssemblySymbol> useSiteInfo; Symbol memberSymbol = GetWellKnownTypeMember(compilation, member, out useSiteInfo, isOptional); diagnostics.Add(useSiteInfo, location ?? syntax.Location); return memberSymbol; } internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, out UseSiteInfo<AssemblySymbol> useSiteInfo, bool isOptional = false) { Symbol memberSymbol = compilation.GetWellKnownTypeMember(member); if ((object)memberSymbol != null) { useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(memberSymbol); if (useSiteInfo.DiagnosticInfo != null) { // Dev11 reports use-site diagnostics even for optional symbols that are found. // We decided to silently ignore bad optional symbols. // Report errors only for non-optional members: if (isOptional) { var severity = useSiteInfo.DiagnosticInfo.Severity; // if the member is optional and bad for whatever reason ignore it: if (severity == DiagnosticSeverity.Error) { useSiteInfo = default; return null; } // ignore warnings: useSiteInfo = new UseSiteInfo<AssemblySymbol>(diagnosticInfo: null, useSiteInfo.PrimaryDependency, useSiteInfo.SecondaryDependencies); } } } else if (!isOptional) { // member is missing MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member); useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name)); } else { useSiteInfo = default; } return memberSymbol; } private class ConsistentSymbolOrder : IComparer<Symbol> { public static readonly ConsistentSymbolOrder Instance = new ConsistentSymbolOrder(); public int Compare(Symbol fst, Symbol snd) { if (snd == fst) return 0; if ((object)fst == null) return -1; if ((object)snd == null) return 1; if (snd.Name != fst.Name) return string.CompareOrdinal(fst.Name, snd.Name); if (snd.Kind != fst.Kind) return (int)fst.Kind - (int)snd.Kind; int aLocationsCount = !snd.Locations.IsDefault ? snd.Locations.Length : 0; int bLocationsCount = fst.Locations.Length; if (aLocationsCount != bLocationsCount) return aLocationsCount - bLocationsCount; if (aLocationsCount == 0 && bLocationsCount == 0) return Compare(fst.ContainingSymbol, snd.ContainingSymbol); Location la = snd.Locations[0]; Location lb = fst.Locations[0]; if (la.IsInSource != lb.IsInSource) return la.IsInSource ? 1 : -1; int containerResult = Compare(fst.ContainingSymbol, snd.ContainingSymbol); if (!la.IsInSource) return containerResult; if (containerResult == 0 && la.SourceTree == lb.SourceTree) return lb.SourceSpan.Start - la.SourceSpan.Start; return containerResult; } } // return the type or namespace symbol in a lookup result, or report an error. internal Symbol ResultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options = default(LookupOptions)) { Symbol symbol = resultSymbol(result, simpleName, arity, where, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (symbol.Kind == SymbolKind.NamedType) { CheckReceiverAndRuntimeSupportForSymbolAccess(where, receiverOpt: null, symbol, diagnostics); if (suppressUseSiteDiagnostics && diagnostics.DependenciesBag is object) { AssemblySymbol container = symbol.ContainingAssembly; if (container is object && container != Compilation.Assembly && container != Compilation.Assembly.CorLibrary) { diagnostics.AddDependency(container); } } } return symbol; Symbol resultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { Debug.Assert(where != null); Debug.Assert(diagnostics != null); var symbols = result.Symbols; wasError = false; if (result.IsMultiViable) { if (symbols.Count > 1) { // gracefully handle symbols.Count > 2 symbols.Sort(ConsistentSymbolOrder.Instance); var originalSymbols = symbols.ToImmutable(); for (int i = 0; i < symbols.Count; i++) { symbols[i] = UnwrapAlias(symbols[i], diagnostics, where); } BestSymbolInfo secondBest; BestSymbolInfo best = GetBestSymbolInfo(symbols, out secondBest); Debug.Assert(!best.IsNone); Debug.Assert(!secondBest.IsNone); if (best.IsFromCompilation && !secondBest.IsFromCompilation) { var srcSymbol = symbols[best.Index]; var mdSymbol = symbols[secondBest.Index]; object arg0; if (best.IsFromSourceModule) { arg0 = srcSymbol.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = srcSymbol.ContainingModule; } //if names match, arities match, and containing symbols match (recursively), ... if (NameAndArityMatchRecursively(srcSymbol, mdSymbol)) { if (srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.NamedType) { // ErrorCode.WRN_SameFullNameThisNsAgg: The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisNsAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.Namespace) { // ErrorCode.WRN_SameFullNameThisAggNs: The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggNs, where.Location, originalSymbols, arg0, srcSymbol, GetContainingAssembly(mdSymbol), mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.NamedType) { // WRN_SameFullNameThisAggAgg: The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else { // namespace would be merged with the source namespace: Debug.Assert(!(srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.Namespace)); } } } var first = symbols[best.Index]; var second = symbols[secondBest.Index]; Debug.Assert(!Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything) || options.IsAttributeTypeLookup(), "This kind of ambiguity is only possible for attributes."); Debug.Assert(!Symbol.Equals(first, second, TypeCompareKind.ConsiderEverything) || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why does the LookupResult contain the same symbol twice?"); CSDiagnosticInfo info; bool reportError; //if names match, arities match, and containing symbols match (recursively), ... if (first != second && NameAndArityMatchRecursively(first, second)) { // suppress reporting the error if we found multiple symbols from source module // since an error has already been reported from the declaration reportError = !(best.IsFromSourceModule && secondBest.IsFromSourceModule); if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType) { if (first.OriginalDefinition == second.OriginalDefinition) { // We imported different generic instantiations of the same generic type // and have an ambiguous reference to a type nested in it reportError = true; // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } else { Debug.Assert(!best.IsFromCorLibrary); // ErrorCode.ERR_SameFullNameAggAgg: The type '{1}' exists in both '{0}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameAggAgg, originalSymbols, new object[] { first.ContainingAssembly, first, second.ContainingAssembly }); // Do not report this error if the first is declared in source and the second is declared in added module, // we already reported declaration error about this name collision. // Do not report this error if both are declared in added modules, // we will report assembly level declaration error about this name collision. if (secondBest.IsFromAddedModule) { Debug.Assert(best.IsFromCompilation); reportError = false; } else if (this.Flags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes) && secondBest.IsFromCorLibrary) { // Ignore duplicate types from the cor library if necessary. // (Specifically the framework assemblies loaded at runtime in // the EE may contain types also available from mscorlib.dll.) return first; } } } else if (first.Kind == SymbolKind.Namespace && second.Kind == SymbolKind.NamedType) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(first), first, second.ContainingAssembly, second }); // Do not report this error if namespace is declared in source and the type is declared in added module, // we already reported declaration error about this name collision. if (best.IsFromSourceModule && secondBest.IsFromAddedModule) { reportError = false; } } else if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.Namespace) { if (!secondBest.IsFromCompilation || secondBest.IsFromSourceModule) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(second), second, first.ContainingAssembly, first }); } else { Debug.Assert(secondBest.IsFromAddedModule); // ErrorCode.ERR_SameFullNameThisAggThisNs: The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}' object arg0; if (best.IsFromSourceModule) { arg0 = first.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = first.ContainingModule; } ModuleSymbol arg2 = second.ContainingModule; // Merged namespaces that span multiple modules don't have a containing module, // so just use module with the smallest ordinal from the containing assembly. if ((object)arg2 == null) { foreach (NamespaceSymbol ns in ((NamespaceSymbol)second).ConstituentNamespaces) { if (ns.ContainingAssembly == Compilation.Assembly) { ModuleSymbol module = ns.ContainingModule; if ((object)arg2 == null || arg2.Ordinal > module.Ordinal) { arg2 = module; } } } } Debug.Assert(arg2.ContainingAssembly == Compilation.Assembly); info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameThisAggThisNs, originalSymbols, new object[] { arg0, first, arg2, second }); } } else if (first.Kind == SymbolKind.RangeVariable && second.Kind == SymbolKind.RangeVariable) { // We will already have reported a conflicting range variable declaration. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } else { // TODO: this is not an appropriate error message here, but used as a fallback until the // appropriate diagnostics are implemented. // '{0}' is an ambiguous reference between '{1}' and '{2}' //info = diagnostics.Add(ErrorCode.ERR_AmbigContext, location, readOnlySymbols, // whereText, // first, // second); // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); reportError = true; } } else { Debug.Assert(originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why was the lookup result viable if it contained non-equal symbols with the same name?"); reportError = true; if (first is NamespaceOrTypeSymbol && second is NamespaceOrTypeSymbol) { if (options.IsAttributeTypeLookup() && first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType && originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name && // Use alias names, if available. Compilation.IsAttributeType((NamedTypeSymbol)first) && Compilation.IsAttributeType((NamedTypeSymbol)second)) { // SPEC: If an attribute class is found both with and without Attribute suffix, an ambiguity // SPEC: is present, and a compile-time error results. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbiguousAttribute, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, first, second }); } else { // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } } else { // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } } wasError = true; if (reportError) { diagnostics.Add(info, where.Location); } return new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(originalSymbols[0]), originalSymbols, LookupResultKind.Ambiguous, info, arity); } else { // Single viable result. var singleResult = symbols[0]; // Cannot reference System.Void directly. var singleType = singleResult as TypeSymbol; if ((object)singleType != null && singleType.PrimitiveTypeCode == Cci.PrimitiveTypeCode.Void && simpleName == "Void") { wasError = true; var errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_SystemVoid); diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(singleResult), singleResult, LookupResultKind.NotReferencable, errorInfo); // UNDONE: Review resultkind. } // Check for bad symbol. else { if (singleResult.Kind == SymbolKind.NamedType && ((SourceModuleSymbol)this.Compilation.SourceModule).AnyReferencedAssembliesAreLinked) { // Complain about unembeddable types from linked assemblies. if (diagnostics.DiagnosticBag is object) { Emit.NoPia.EmbeddedTypesManager.IsValidEmbeddableType((NamedTypeSymbol)singleResult, where, diagnostics.DiagnosticBag); } } if (!suppressUseSiteDiagnostics) { wasError = ReportUseSite(singleResult, diagnostics, where); } else if (singleResult.Kind == SymbolKind.ErrorType) { // We want to report ERR_CircularBase error on the spot to make sure // that the right location is used for it. var errorType = (ErrorTypeSymbol)singleResult; if (errorType.Unreported) { DiagnosticInfo errorInfo = errorType.ErrorInfo; if (errorInfo != null && errorInfo.Code == (int)ErrorCode.ERR_CircularBase) { wasError = true; diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(errorType), errorType.Name, errorType.Arity, errorInfo, unreported: false); } } } } return singleResult; } } // Below here is the error case; no viable symbols found (but maybe one or more non-viable.) wasError = true; if (result.Kind == LookupResultKind.Empty) { string aliasOpt = null; SyntaxNode node = where; while (node is ExpressionSyntax) { if (node.Kind() == SyntaxKind.AliasQualifiedName) { aliasOpt = ((AliasQualifiedNameSyntax)node).Alias.Identifier.ValueText; break; } node = node.Parent; } CSDiagnosticInfo info = NotFound(where, simpleName, arity, (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, diagnostics, aliasOpt, qualifierOpt, options); return new ExtendedErrorTypeSymbol(qualifierOpt ?? Compilation.Assembly.GlobalNamespace, simpleName, arity, info); } Debug.Assert(symbols.Count > 0); // Report any errors we encountered with the symbol we looked up. if (!suppressUseSiteDiagnostics) { for (int i = 0; i < symbols.Count; i++) { ReportUseSite(symbols[i], diagnostics, where); } } // result.Error might be null if we have already generated parser errors, // e.g. when generic name is used for attribute name. if (result.Error != null && ((object)qualifierOpt == null || qualifierOpt.Kind != SymbolKind.ErrorType)) // Suppress cascading. { diagnostics.Add(new CSDiagnostic(result.Error, where.Location)); } if ((symbols.Count > 1) || (symbols[0] is NamespaceOrTypeSymbol || symbols[0] is AliasSymbol) || result.Kind == LookupResultKind.NotATypeOrNamespace || result.Kind == LookupResultKind.NotAnAttributeType) { // Bad type or namespace (or things expected as types/namespaces) are packaged up as error types, preserving the symbols and the result kind. // We do this if there are multiple symbols too, because just returning one would be losing important information, and they might // be of different kinds. return new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), result.Kind, result.Error, arity); } else { // It's a single non-type-or-namespace; error was already reported, so just return it. return symbols[0]; } } } private static AssemblySymbol GetContainingAssembly(Symbol symbol) { // Merged namespaces that span multiple assemblies don't have a containing assembly, // so just use the containing assembly of the first constituent. return symbol.ContainingAssembly ?? ((NamespaceSymbol)symbol).ConstituentNamespaces.First().ContainingAssembly; } [Flags] private enum BestSymbolLocation { None, FromSourceModule, FromAddedModule, FromReferencedAssembly, FromCorLibrary, } [DebuggerDisplay("Location = {_location}, Index = {_index}")] private struct BestSymbolInfo { private readonly BestSymbolLocation _location; private readonly int _index; /// <summary> /// Returns -1 if None. /// </summary> public int Index { get { return IsNone ? -1 : _index; } } public bool IsFromSourceModule { get { return _location == BestSymbolLocation.FromSourceModule; } } public bool IsFromAddedModule { get { return _location == BestSymbolLocation.FromAddedModule; } } public bool IsFromCompilation { get { return (_location == BestSymbolLocation.FromSourceModule) || (_location == BestSymbolLocation.FromAddedModule); } } public bool IsNone { get { return _location == BestSymbolLocation.None; } } public bool IsFromCorLibrary { get { return _location == BestSymbolLocation.FromCorLibrary; } } public BestSymbolInfo(BestSymbolLocation location, int index) { Debug.Assert(location != BestSymbolLocation.None); _location = location; _index = index; } /// <summary> /// Prefers symbols from source module, then from added modules, then from referenced assemblies. /// Returns true if values were swapped. /// </summary> public static bool Sort(ref BestSymbolInfo first, ref BestSymbolInfo second) { if (IsSecondLocationBetter(first._location, second._location)) { BestSymbolInfo temp = first; first = second; second = temp; return true; } return false; } /// <summary> /// Returns true if the second is a better location than the first. /// </summary> public static bool IsSecondLocationBetter(BestSymbolLocation firstLocation, BestSymbolLocation secondLocation) { Debug.Assert(secondLocation != 0); return (firstLocation == BestSymbolLocation.None) || (firstLocation > secondLocation); } } /// <summary> /// Prefer symbols from source module, then from added modules, then from referenced assemblies. /// </summary> private BestSymbolInfo GetBestSymbolInfo(ArrayBuilder<Symbol> symbols, out BestSymbolInfo secondBest) { BestSymbolInfo first = default(BestSymbolInfo); BestSymbolInfo second = default(BestSymbolInfo); var compilation = this.Compilation; for (int i = 0; i < symbols.Count; i++) { var symbol = symbols[i]; BestSymbolLocation location; if (symbol.Kind == SymbolKind.Namespace) { location = BestSymbolLocation.None; foreach (var ns in ((NamespaceSymbol)symbol).ConstituentNamespaces) { var current = GetLocation(compilation, ns); if (BestSymbolInfo.IsSecondLocationBetter(location, current)) { location = current; if (location == BestSymbolLocation.FromSourceModule) { break; } } } } else { location = GetLocation(compilation, symbol); } var third = new BestSymbolInfo(location, i); if (BestSymbolInfo.Sort(ref second, ref third)) { BestSymbolInfo.Sort(ref first, ref second); } } Debug.Assert(!first.IsNone); Debug.Assert(!second.IsNone); secondBest = second; return first; } private static BestSymbolLocation GetLocation(CSharpCompilation compilation, Symbol symbol) { var containingAssembly = symbol.ContainingAssembly; if (containingAssembly == compilation.SourceAssembly) { return (symbol.ContainingModule == compilation.SourceModule) ? BestSymbolLocation.FromSourceModule : BestSymbolLocation.FromAddedModule; } else { return (containingAssembly == containingAssembly.CorLibrary) ? BestSymbolLocation.FromCorLibrary : BestSymbolLocation.FromReferencedAssembly; } } /// <remarks> /// This is only intended to be called when the type isn't found (i.e. not when it is found but is inaccessible, has the wrong arity, etc). /// </remarks> private CSDiagnosticInfo NotFound(SyntaxNode where, string simpleName, int arity, string whereText, BindingDiagnosticBag diagnostics, string aliasOpt, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { var location = where.Location; // Lookup totally ignores type forwarders, but we want the type lookup diagnostics // to distinguish between a type that can't be found and a type that is only present // as a type forwarder. We'll look for type forwarders in the containing and // referenced assemblies and report more specific diagnostics if they are found. AssemblySymbol forwardedToAssembly; // for attributes, suggest both, but not for verbatim name if (options.IsAttributeTypeLookup() && !options.IsVerbatimNameAttributeTypeLookup()) { // just recurse one level, so cheat and OR verbatim name option :) NotFound(where, simpleName, arity, whereText + "Attribute", diagnostics, aliasOpt, qualifierOpt, options | LookupOptions.VerbatimNameAttributeTypeOnly); } if ((object)qualifierOpt != null) { if (qualifierOpt.IsType) { var errorQualifier = qualifierOpt as ErrorTypeSymbol; if ((object)errorQualifier != null && errorQualifier.ErrorInfo != null) { return (CSDiagnosticInfo)errorQualifier.ErrorInfo; } return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, location, whereText, qualifierOpt); } else { Debug.Assert(qualifierOpt.IsNamespace); forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if (ReferenceEquals(qualifierOpt, Compilation.GlobalNamespace)) { Debug.Assert(aliasOpt == null || aliasOpt == SyntaxFacts.GetText(SyntaxKind.GlobalKeyword)); return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFound, location, whereText, qualifierOpt) : diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly); } else { object container = qualifierOpt; // If there was an alias (e.g. A::C) and the given qualifier is the global namespace of the alias, // then use the alias name in the error message, since it's more helpful than "<global namespace>". if (aliasOpt != null && qualifierOpt.IsNamespace && ((NamespaceSymbol)qualifierOpt).IsGlobalNamespace) { container = aliasOpt; } return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNS, location, whereText, container) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, container, forwardedToAssembly); } } } if (options == LookupOptions.NamespaceAliasesOnly) { return diagnostics.Add(ErrorCode.ERR_AliasNotFound, location, whereText); } if ((where as IdentifierNameSyntax)?.Identifier.Text == "var" && !options.IsAttributeTypeLookup()) { var code = (where.Parent is QueryClauseSyntax) ? ErrorCode.ERR_TypeVarNotFoundRangeVariable : ErrorCode.ERR_TypeVarNotFound; return diagnostics.Add(code, location); } forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if ((object)forwardedToAssembly != null) { return qualifierOpt == null ? diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, qualifierOpt, forwardedToAssembly); } return diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFound, location, whereText); } protected virtual AssemblySymbol GetForwardedToAssemblyInUsingNamespaces(string metadataName, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { return Next?.GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } protected AssemblySymbol GetForwardedToAssembly(string fullName, BindingDiagnosticBag diagnostics, Location location) { var metadataName = MetadataTypeName.FromFullName(fullName); foreach (var referencedAssembly in Compilation.Assembly.Modules[0].GetReferencedAssemblySymbols()) { var forwardedType = referencedAssembly.TryLookupForwardedMetadataType(ref metadataName); if ((object)forwardedType != null) { if (forwardedType.Kind == SymbolKind.ErrorType) { DiagnosticInfo diagInfo = ((ErrorTypeSymbol)forwardedType).ErrorInfo; if (diagInfo.Code == (int)ErrorCode.ERR_CycleInTypeForwarder) { Debug.Assert((object)forwardedType.ContainingAssembly != null, "How did we find a cycle if there was no forwarding?"); diagnostics.Add(ErrorCode.ERR_CycleInTypeForwarder, location, fullName, forwardedType.ContainingAssembly.Name); } else if (diagInfo.Code == (int)ErrorCode.ERR_TypeForwardedToMultipleAssemblies) { diagnostics.Add(diagInfo, location); return null; // Cannot determine a suitable forwarding assembly } } return forwardedType.ContainingAssembly; } } return null; } /// <summary> /// Look for a type forwarder for the given type in the containing assembly and any referenced assemblies. /// </summary> /// <param name="name">The name of the (potentially) forwarded type.</param> /// <param name="arity">The arity of the forwarded type.</param> /// <param name="qualifierOpt">The namespace of the potentially forwarded type. If none is provided, will /// try Usings of the current import for eligible namespaces and return the namespace of the found forwarder, /// if any.</param> /// <param name="diagnostics">Will be used to report non-fatal errors during look up.</param> /// <param name="location">Location to report errors on.</param> /// <returns>Returns the Assembly to which the type is forwarded, or null if none is found.</returns> /// <remarks> /// Since this method is intended to be used for error reporting, it stops as soon as it finds /// any type forwarder (or an error to report). It does not check other assemblies for consistency or better results. /// </remarks> protected AssemblySymbol GetForwardedToAssembly(string name, int arity, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { // If we are in the process of binding assembly level attributes, we might get into an infinite cycle // if any of the referenced assemblies forwards type to this assembly. Since forwarded types // are specified through assembly level attributes, an attempt to resolve the forwarded type // might require us to examine types forwarded by this assembly, thus binding assembly level // attributes again. And the cycle continues. // So, we won't do the analysis in this case, at the expense of better diagnostics. if ((this.Flags & BinderFlags.InContextualAttributeBinder) != 0) { var current = this; do { var contextualAttributeBinder = current as ContextualAttributeBinder; if (contextualAttributeBinder != null) { if ((object)contextualAttributeBinder.AttributeTarget != null && contextualAttributeBinder.AttributeTarget.Kind == SymbolKind.Assembly) { return null; } break; } current = current.Next; } while (current != null); } // NOTE: This won't work if the type isn't using CLS-style generic naming (i.e. `arity), but this code is // only intended to improve diagnostic messages, so false negatives in corner cases aren't a big deal. var metadataName = MetadataHelpers.ComposeAritySuffixedMetadataName(name, arity); var fullMetadataName = MetadataHelpers.BuildQualifiedName(qualifierOpt?.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), metadataName); var result = GetForwardedToAssembly(fullMetadataName, diagnostics, location); if ((object)result != null) { return result; } if ((object)qualifierOpt == null) { return GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } return null; } #nullable enable internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, BindingDiagnosticBag diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, DiagnosticBag? diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax.SyntaxTree, feature, diagnostics, location ?? syntax.GetLocation()); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, BindingDiagnosticBag diagnostics, Location location) { return CheckFeatureAvailability(tree, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, DiagnosticBag? diagnostics, Location location) { if (feature.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)tree.Options) is { } diagInfo) { diagnostics?.Add(diagInfo, location); return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); return isVar ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "unmanaged" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="keyword"> /// Set to <see cref="ConstraintContextualKeyword.None"/> if syntax binds to a type in the current context, otherwise /// syntax binds to the corresponding keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to a contextual constraint keyword. /// </returns> private TypeWithAnnotations BindTypeOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { var symbol = BindTypeOrAliasOrConstraintKeyword(syntax, diagnostics, out keyword); Debug.Assert((keyword != ConstraintContextualKeyword.None) == symbol.IsDefault); return (keyword != ConstraintContextualKeyword.None) ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <param name="alias">Alias symbol if syntax binds to an alias.</param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar, out AliasSymbol alias) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); if (isVar) { alias = null; return default; } else { return UnwrapAlias(symbol, out alias, diagnostics, syntax).TypeWithAnnotations; } } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type or alias to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type or alias if syntax binds to a type or alias to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { if (syntax.IsVar) { var symbol = BindTypeOrAliasOrKeyword((IdentifierNameSyntax)syntax, diagnostics, out isVar); if (isVar) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImplicitLocal, diagnostics); } return symbol; } else { isVar = false; return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } private enum ConstraintContextualKeyword { None, Unmanaged, NotNull, } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { if (syntax.IsUnmanaged) { keyword = ConstraintContextualKeyword.Unmanaged; } else if (syntax.IsNotNull) { keyword = ConstraintContextualKeyword.NotNull; } else { keyword = ConstraintContextualKeyword.None; } if (keyword != ConstraintContextualKeyword.None) { var identifierSyntax = (IdentifierNameSyntax)syntax; var symbol = BindTypeOrAliasOrKeyword(identifierSyntax, diagnostics, out bool isKeyword); if (isKeyword) { switch (keyword) { case ConstraintContextualKeyword.Unmanaged: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureUnmanagedGenericTypeConstraint, diagnostics); break; case ConstraintContextualKeyword.NotNull: CheckFeatureAvailability(identifierSyntax, MessageID.IDS_FeatureNotNullGenericTypeConstraint, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(keyword); } } else { keyword = ConstraintContextualKeyword.None; } return symbol; } else { return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } /// <summary> /// Binds the type for the syntax taking into account possibility of the type being a keyword. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// PREREQUISITE: syntax should be checked to match the keyword, like <see cref="TypeSyntax.IsVar"/> or <see cref="TypeSyntax.IsUnmanaged"/>. /// Otherwise, call <see cref="Binder.BindTypeOrAlias(ExpressionSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> instead. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(IdentifierNameSyntax syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { return BindTypeOrAliasOrKeyword(((IdentifierNameSyntax)syntax).Identifier, syntax, diagnostics, out isKeyword); } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(SyntaxToken identifier, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { // Keywords can only be IdentifierNameSyntax var identifierValueText = identifier.ValueText; Symbol symbol = null; // Perform name lookup without generating diagnostics as it could possibly be a keyword in the current context. var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsInternal(lookupResult, identifierValueText, arity: 0, useSiteInfo: ref discardedUseSiteInfo, basesBeingResolved: null, options: LookupOptions.NamespacesOrTypesOnly, diagnose: false); // We have following possible cases for lookup: // 1) LookupResultKind.Empty: must be a keyword // 2) LookupResultKind.Viable: // a) Single viable result that corresponds to 1) a non-error type: cannot be a keyword // 2) an error type: must be a keyword // b) Single viable result that corresponds to namespace: must be a keyword // c) Multi viable result (ambiguous result), we must return an error type: cannot be a keyword // 3) Non viable, non empty lookup result: must be a keyword // BREAKING CHANGE: Case (2)(c) is a breaking change from the native compiler. // BREAKING CHANGE: Native compiler interprets lookup with ambiguous result to correspond to bind // BREAKING CHANGE: to "var" keyword (isVar = true), rather than reporting an error. // BREAKING CHANGE: See test SemanticErrorTests.ErrorMeansSuccess_var() for an example. switch (lookupResult.Kind) { case LookupResultKind.Empty: // Case (1) isKeyword = true; symbol = null; break; case LookupResultKind.Viable: // Case (2) var resultDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); bool wasError; symbol = ResultSymbol( lookupResult, identifierValueText, arity: 0, where: syntax, diagnostics: resultDiagnostics, suppressUseSiteDiagnostics: false, wasError: out wasError, qualifierOpt: null); // Here, we're mimicking behavior of dev10. If the identifier fails to bind // as a type, even if the reason is (e.g.) a type/alias conflict, then treat // it as the contextual keyword. if (wasError && lookupResult.IsSingleViable) { // NOTE: don't report diagnostics - we're not going to use the lookup result. resultDiagnostics.DiagnosticBag.Free(); // Case (2)(a)(2) goto default; } diagnostics.AddRange(resultDiagnostics.DiagnosticBag); resultDiagnostics.DiagnosticBag.Free(); if (lookupResult.IsSingleViable) { var type = UnwrapAlias(symbol, diagnostics, syntax) as TypeSymbol; if ((object)type != null) { // Case (2)(a)(1) isKeyword = false; } else { // Case (2)(b) Debug.Assert(UnwrapAliasNoDiagnostics(symbol) is NamespaceSymbol); isKeyword = true; symbol = null; } } else { // Case (2)(c) isKeyword = false; } break; default: // Case (3) isKeyword = true; symbol = null; break; } lookupResult.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(identifier), symbol); } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it unwraps the alias // and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); return UnwrapAlias(symbol, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it stores the AliasSymbol in // the alias parameter, unwraps the alias and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, out AliasSymbol alias, ConsList<TypeSymbol> basesBeingResolved = null) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved); return UnwrapAlias(symbol, out alias, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type or an Alias to Type // and returns the resultant symbol. // NOTE: This method doesn't unwrap aliases. internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAlias(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { Debug.Assert(diagnostics != null); var symbol = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null || suppressUseSiteDiagnostics); // symbol must be a TypeSymbol or an Alias to a TypeSymbol if (symbol.IsType || (symbol.IsAlias && UnwrapAliasNoDiagnostics(symbol.Symbol, basesBeingResolved) is TypeSymbol)) { if (symbol.IsType) { // Obsolete alias targets are reported in UnwrapAlias, but if it was a type (not an // alias to a type) we report the obsolete type here. symbol.TypeWithAnnotations.ReportDiagnosticsIfObsolete(this, syntax, diagnostics); } return symbol; } var diagnosticInfo = diagnostics.Add(ErrorCode.ERR_BadSKknown, syntax.Location, syntax, symbol.Symbol.GetKindText(), MessageID.IDS_SK_TYPE.Localize()); return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbol.Symbol), symbol.Symbol, LookupResultKind.NotATypeOrNamespace, diagnosticInfo)); } /// <summary> /// The immediately containing namespace or named type, or the global /// namespace if containing symbol is neither a namespace or named type. /// </summary> private NamespaceOrTypeSymbol GetContainingNamespaceOrType(Symbol symbol) { return symbol.ContainingNamespaceOrType() ?? this.Compilation.Assembly.GlobalNamespace; } internal Symbol BindNamespaceAliasSymbol(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (node.Identifier.Kind() == SyntaxKind.GlobalKeyword) { return this.Compilation.GlobalNamespaceAlias; } else { bool wasError; var plainName = node.Identifier.ValueText; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, plainName, 0, ref useSiteInfo, null, LookupOptions.NamespaceAliasesOnly); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = ResultSymbol(result, plainName, 0, node, diagnostics, false, out wasError, qualifierOpt: null, options: LookupOptions.NamespaceAliasesOnly); result.Free(); return bindingResult; } } internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { return BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null); } /// <summary> /// This method is used in deeply recursive parts of the compiler and requires a non-trivial amount of stack /// space to execute. Preventing inlining here to keep recursive frames small. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var result = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); Debug.Assert(!result.IsDefault); return UnwrapAlias(result, diagnostics, syntax, basesBeingResolved); } #nullable enable /// <summary> /// Bind the syntax into a namespace, type or alias symbol. /// </summary> /// <remarks> /// This method is used in deeply recursive parts of the compiler. Specifically this and /// <see cref="BindQualifiedName(ExpressionSyntax, SimpleNameSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> /// are mutually recursive. The non-recursive parts of this method tend to reserve significantly large /// stack frames due to their use of large struct like <see cref="TypeWithAnnotations"/>. /// /// To keep the stack frame size on recursive paths small the non-recursive parts are factored into local /// functions. This means we pay their stack penalty only when they are used. They are themselves big /// enough they should be disqualified from inlining. In the future when attributes are allowed on /// local functions we should explicitly mark them as <see cref="MethodImplOptions.NoInlining"/> /// </remarks> internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeOrAliasSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { switch (syntax.Kind()) { case SyntaxKind.NullableType: return bindNullable(); case SyntaxKind.PredefinedType: return bindPredefined(); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt: null); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt: null); case SyntaxKind.AliasQualifiedName: return bindAlias(); case SyntaxKind.QualifiedName: { var node = (QualifiedNameSyntax)syntax; return BindQualifiedName(node.Left, node.Right, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.SimpleMemberAccessExpression: { var node = (MemberAccessExpressionSyntax)syntax; return BindQualifiedName(node.Expression, node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.ArrayType: { return BindArrayType((ArrayTypeSyntax)syntax, diagnostics, permitDimensions: false, basesBeingResolved, disallowRestrictedTypes: true); } case SyntaxKind.PointerType: return bindPointer(); case SyntaxKind.FunctionPointerType: var functionPointerTypeSyntax = (FunctionPointerTypeSyntax)syntax; if (GetUnsafeDiagnosticInfo(sizeOfTypeOpt: null) is CSDiagnosticInfo info) { var @delegate = functionPointerTypeSyntax.DelegateKeyword; var asterisk = functionPointerTypeSyntax.AsteriskToken; RoslynDebug.Assert(@delegate.SyntaxTree is object); diagnostics.Add(info, Location.Create(@delegate.SyntaxTree, TextSpan.FromBounds(@delegate.SpanStart, asterisk.Span.End))); } return TypeWithAnnotations.Create( FunctionPointerTypeSymbol.CreateFromSource( functionPointerTypeSyntax, this, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics)); case SyntaxKind.OmittedTypeArgument: { return BindTypeArgument((TypeSyntax)syntax, diagnostics, basesBeingResolved); } case SyntaxKind.TupleType: { var tupleTypeSyntax = (TupleTypeSyntax)syntax; return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(tupleTypeSyntax.CloseParenToken), BindTupleType(tupleTypeSyntax, diagnostics, basesBeingResolved)); } case SyntaxKind.RefType: { // ref needs to be handled by the caller var refTypeSyntax = (RefTypeSyntax)syntax; var refToken = refTypeSyntax.RefKeyword; if (!syntax.HasErrors) { diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refToken.GetLocation(), refToken.ToString()); } return BindNamespaceOrTypeOrAliasSymbol(refTypeSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } default: { // This is invalid syntax for a type. This arises when a constant pattern that fails to bind // is attempted to be bound as a type pattern. return createErrorType(); } } void reportNullableReferenceTypesIfNeeded(SyntaxToken questionToken, TypeWithAnnotations typeArgument = default) { bool isNullableEnabled = AreNullableAnnotationsEnabled(questionToken); bool isGeneratedCode = IsGeneratedCode(questionToken); var location = questionToken.GetLocation(); if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { // Inside a method body or other executable code, we can question IsValueType without causing cycles. if (typeArgument.HasType && !ShouldCheckConstraints) { LazyMissingNonNullTypesContextDiagnosticInfo.AddAll( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } else { LazyMissingNonNullTypesContextDiagnosticInfo.ReportNullableReferenceTypesIfNeeded( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } } } NamespaceOrTypeOrAliasSymbolWithAnnotations bindNullable() { var nullableSyntax = (NullableTypeSyntax)syntax; TypeSyntax typeArgumentSyntax = nullableSyntax.ElementType; TypeWithAnnotations typeArgument = BindType(typeArgumentSyntax, diagnostics, basesBeingResolved); TypeWithAnnotations constructedType = typeArgument.SetIsAnnotated(Compilation); reportNullableReferenceTypesIfNeeded(nullableSyntax.QuestionToken, typeArgument); if (!ShouldCheckConstraints) { diagnostics.Add(new LazyUseSiteDiagnosticsInfoForNullableType(Compilation.LanguageVersion, constructedType), syntax.GetLocation()); } else if (constructedType.IsNullableType()) { ReportUseSite(constructedType.Type.OriginalDefinition, diagnostics, syntax); var type = (NamedTypeSymbol)constructedType.Type; var location = syntax.Location; type.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: true, location, diagnostics)); } else if (GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(Compilation.LanguageVersion, constructedType) is { } diagnosticInfo) { diagnostics.Add(diagnosticInfo, syntax.Location); } return constructedType; } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPredefined() { var predefinedType = (PredefinedTypeSyntax)syntax; var type = BindPredefinedTypeSymbol(predefinedType, diagnostics); return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(predefinedType.Keyword), type); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindAlias() { var node = (AliasQualifiedNameSyntax)syntax; var bindingResult = BindNamespaceAliasSymbol(node.Alias, diagnostics); var alias = bindingResult as AliasSymbol; NamespaceOrTypeSymbol left = (alias is object) ? alias.Target : (NamespaceOrTypeSymbol)bindingResult; if (left.Kind == SymbolKind.NamedType) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(left, LookupResultKind.NotATypeOrNamespace, diagnostics.Add(ErrorCode.ERR_ColColWithTypeAlias, node.Alias.Location, node.Alias.Identifier.Text))); } return this.BindSimpleNamespaceOrTypeOrAliasSymbol(node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPointer() { var node = (PointerTypeSyntax)syntax; var elementType = BindType(node.ElementType, diagnostics, basesBeingResolved); ReportUnsafeIfNotAllowed(node, diagnostics); if (!Flags.HasFlag(BinderFlags.SuppressConstraintChecks)) { CheckManagedAddr(Compilation, elementType.Type, node.Location, diagnostics); } return TypeWithAnnotations.Create(new PointerTypeSymbol(elementType)); } NamespaceOrTypeOrAliasSymbolWithAnnotations createErrorType() { diagnostics.Add(ErrorCode.ERR_TypeExpected, syntax.GetLocation()); return TypeWithAnnotations.Create(CreateErrorType()); } } internal static CSDiagnosticInfo? GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(LanguageVersion languageVersion, in TypeWithAnnotations type) { if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8()) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); if (requiredVersion > languageVersion) { return new CSDiagnosticInfo(ErrorCode.ERR_NullableUnconstrainedTypeParameter, new CSharpRequiredLanguageVersion(requiredVersion)); } } return null; } #nullable disable private TypeWithAnnotations BindArrayType( ArrayTypeSyntax node, BindingDiagnosticBag diagnostics, bool permitDimensions, ConsList<TypeSymbol> basesBeingResolved, bool disallowRestrictedTypes) { TypeWithAnnotations type = BindType(node.ElementType, diagnostics, basesBeingResolved); if (type.IsStatic) { // CS0719: '{0}': array elements cannot be of static type Error(diagnostics, ErrorCode.ERR_ArrayOfStaticClass, node.ElementType, type.Type); } if (disallowRestrictedTypes) { // Restricted types cannot be on the heap, but they can be on the stack, so are allowed in a stackalloc if (ShouldCheckConstraints) { if (type.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node.ElementType, type.Type); } } else { diagnostics.Add(new LazyArrayElementCantBeRefAnyDiagnosticInfo(type), node.ElementType.GetLocation()); } } for (int i = node.RankSpecifiers.Count - 1; i >= 0; i--) { var rankSpecifier = node.RankSpecifiers[i]; var dimension = rankSpecifier.Sizes; if (!permitDimensions && dimension.Count != 0 && dimension[0].Kind() != SyntaxKind.OmittedArraySizeExpression) { // https://github.com/dotnet/roslyn/issues/32464 // Should capture invalid dimensions for use in `SemanticModel` and `IOperation`. Error(diagnostics, ErrorCode.ERR_ArraySizeInDeclaration, rankSpecifier); } var array = ArrayTypeSymbol.CreateCSharpArray(this.Compilation.Assembly, type, rankSpecifier.Rank); type = TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(rankSpecifier.CloseBracketToken), array); } return type; } private TypeSymbol BindTupleType(TupleTypeSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved) { int numElements = syntax.Elements.Count; var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(numElements); var locations = ArrayBuilder<Location>.GetInstance(numElements); ArrayBuilder<string> elementNames = null; // set of names already used var uniqueFieldNames = PooledHashSet<string>.GetInstance(); bool hasExplicitNames = false; for (int i = 0; i < numElements; i++) { var argumentSyntax = syntax.Elements[i]; var argumentType = BindType(argumentSyntax.Type, diagnostics, basesBeingResolved); types.Add(argumentType); string name = null; SyntaxToken nameToken = argumentSyntax.Identifier; if (nameToken.Kind() == SyntaxKind.IdentifierToken) { name = nameToken.ValueText; // validate name if we have one hasExplicitNames = true; CheckTupleMemberName(name, i, nameToken, diagnostics, uniqueFieldNames); locations.Add(nameToken.GetLocation()); } else { locations.Add(argumentSyntax.Location); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); } uniqueFieldNames.Free(); if (hasExplicitNames) { // If the tuple type with names is bound we must have the TupleElementNamesAttribute to emit // it is typically there though, if we have ValueTuple at all ReportMissingTupleElementNamesAttributesIfNeeded(Compilation, syntax.GetLocation(), diagnostics); } var typesArray = types.ToImmutableAndFree(); var locationsArray = locations.ToImmutableAndFree(); if (typesArray.Length < 2) { throw ExceptionUtilities.UnexpectedValue(typesArray.Length); } bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); return NamedTypeSymbol.CreateTuple(syntax.Location, typesArray, locationsArray, elementNames == null ? default(ImmutableArray<string>) : elementNames.ToImmutableAndFree(), this.Compilation, this.ShouldCheckConstraints, includeNullability: this.ShouldCheckConstraints && includeNullability, errorPositions: default(ImmutableArray<bool>), syntax: syntax, diagnostics: diagnostics); } internal static void ReportMissingTupleElementNamesAttributesIfNeeded(CSharpCompilation compilation, Location location, BindingDiagnosticBag diagnostics) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!compilation.HasTupleNamesAttributes(bag, location)) { var info = new CSDiagnosticInfo(ErrorCode.ERR_TupleElementNamesAttributeMissing, AttributeDescription.TupleElementNamesAttribute.FullName); Error(diagnostics, info, location); } else { diagnostics.AddRange(bag); } bag.Free(); } private static void CollectTupleFieldMemberName(string name, int elementIndex, int tupleSize, ref ArrayBuilder<string> elementNames) { // add the name to the list // names would typically all be there or none at all // but in case we need to handle this in error cases if (elementNames != null) { elementNames.Add(name); } else { if (name != null) { elementNames = ArrayBuilder<string>.GetInstance(tupleSize); for (int j = 0; j < elementIndex; j++) { elementNames.Add(null); } elementNames.Add(name); } } } private static bool CheckTupleMemberName(string name, int index, SyntaxNodeOrToken syntax, BindingDiagnosticBag diagnostics, PooledHashSet<string> uniqueFieldNames) { int reserved = NamedTypeSymbol.IsTupleElementNameReserved(name); if (reserved == 0) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementNameAnyPosition, syntax, name); return false; } else if (reserved > 0 && reserved != index + 1) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementName, syntax, name, reserved); return false; } else if (!uniqueFieldNames.Add(name)) { Error(diagnostics, ErrorCode.ERR_TupleDuplicateElementName, syntax); return false; } return true; } private NamedTypeSymbol BindPredefinedTypeSymbol(PredefinedTypeSyntax node, BindingDiagnosticBag diagnostics) { return GetSpecialType(node.Keyword.Kind().GetSpecialType(), diagnostics, node); } /// <summary> /// Binds a simple name or the simple name portion of a qualified name. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindSimpleNamespaceOrTypeOrAliasSymbol( SimpleNameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt = null) { // Note that the comment above is a small lie; there is no such thing as the "simple name portion" of // a qualified alias member expression. A qualified alias member expression has the form // "identifier :: identifier optional-type-arguments" -- the right hand side of which // happens to match the syntactic form of a simple name. As a convenience, we analyze the // right hand side of the "::" here because it is so similar to a simple name; the left hand // side is in qualifierOpt. switch (syntax.Kind()) { default: return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(qualifierOpt ?? this.Compilation.Assembly.GlobalNamespace, string.Empty, arity: 0, errorInfo: null)); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt); } } private static bool IsViableType(LookupResult result) { if (!result.IsMultiViable) { return false; } foreach (var s in result.Symbols) { switch (s.Kind) { case SymbolKind.Alias: if (((AliasSymbol)s).Target.Kind == SymbolKind.NamedType) return true; break; case SymbolKind.NamedType: case SymbolKind.TypeParameter: return true; } } return false; } protected NamespaceOrTypeOrAliasSymbolWithAnnotations BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol( IdentifierNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt) { var identifierValueText = node.Identifier.ValueText; // If we are here in an error-recovery scenario, say, "goo<int, >(123);" then // we might have an 'empty' simple name. In that case do not report an // 'unable to find ""' error; we've already reported an error in the parser so // just bail out with an error symbol. if (string.IsNullOrWhiteSpace(identifierValueText)) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol( Compilation.Assembly.GlobalNamespace, identifierValueText, 0, new CSDiagnosticInfo(ErrorCode.ERR_SingleTypeNameNotFound))); } var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, identifierValueText, 0, diagnostics); if ((object)errorResult != null) { return TypeWithAnnotations.Create(errorResult); } var result = LookupResult.GetInstance(); LookupOptions options = GetSimpleNameLookupOptions(node, node.Identifier.IsVerbatimIdentifier()); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(result, qualifierOpt, identifierValueText, 0, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = null; // If we were looking up "dynamic" or "nint" at the topmost level and didn't find anything good, // use that particular type (assuming the /langversion is supported). if ((object)qualifierOpt == null && !IsViableType(result)) { if (node.Identifier.ValueText == "dynamic") { if ((node.Parent == null || node.Parent.Kind() != SyntaxKind.Attribute && // dynamic not allowed as attribute type SyntaxFacts.IsInTypeOnlyContext(node)) && Compilation.LanguageVersion >= MessageID.IDS_FeatureDynamic.RequiredVersion()) { bindingResult = Compilation.DynamicType; ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } else { bindingResult = BindNativeIntegerSymbolIfAny(node, diagnostics); } } if (bindingResult is null) { bool wasError; bindingResult = ResultSymbol(result, identifierValueText, 0, node, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (bindingResult.Kind == SymbolKind.Alias) { var aliasTarget = ((AliasSymbol)bindingResult).GetAliasTarget(basesBeingResolved); if (aliasTarget.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)aliasTarget).ContainsDynamic()) { ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } } result.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(node.Identifier), bindingResult); } /// <summary> /// If the node is "nint" or "nuint" and not alone inside nameof, return the corresponding native integer symbol. /// Otherwise return null. /// </summary> private NamedTypeSymbol BindNativeIntegerSymbolIfAny(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { SpecialType specialType; switch (node.Identifier.Text) { case "nint": specialType = SpecialType.System_IntPtr; break; case "nuint": specialType = SpecialType.System_UIntPtr; break; default: return null; } switch (node.Parent) { case AttributeSyntax parent when parent.Name == node: // [nint] return null; case UsingDirectiveSyntax parent when parent.Name == node: // using nint; using A = nuint; return null; case ArgumentSyntax parent when // nameof(nint) (IsInsideNameof && parent.Parent?.Parent is InvocationExpressionSyntax invocation && (invocation.Expression as IdentifierNameSyntax)?.Identifier.ContextualKind() == SyntaxKind.NameOfKeyword): // Don't bind nameof(nint) or nameof(nuint) so that ERR_NameNotInContext is reported. return null; } CheckFeatureAvailability(node, MessageID.IDS_FeatureNativeInt, diagnostics); return this.GetSpecialType(specialType, diagnostics, node).AsNativeInteger(); } private void ReportUseSiteDiagnosticForDynamic(BindingDiagnosticBag diagnostics, IdentifierNameSyntax node) { // Dynamic type might be bound in a declaration context where we need to synthesize the DynamicAttribute. // Here we report the use site error (ERR_DynamicAttributeMissing) for missing DynamicAttribute type or it's constructors. // // BREAKING CHANGE: Native compiler reports ERR_DynamicAttributeMissing at emit time when synthesizing DynamicAttribute. // Currently, in Roslyn we don't support reporting diagnostics while synthesizing attributes, these diagnostics are reported at bind time. // Hence, we report this diagnostic here. Note that DynamicAttribute has two constructors, and either of them may be used while // synthesizing the DynamicAttribute (see DynamicAttributeEncoder.Encode method for details). // However, unlike the native compiler which reports use site diagnostic only for the specific DynamicAttribute constructor which is going to be used, // we report it for both the constructors and also for boolean type (used by the second constructor). // This is a breaking change for the case where only one of the two constructor of DynamicAttribute is missing, but we never use it for any of the synthesized DynamicAttributes. // However, this seems like a very unlikely scenario and an acceptable break. if (node.IsTypeInContextWhichNeedsDynamicAttribute()) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!Compilation.HasDynamicEmitAttributes(bag, node.Location)) { // CONSIDER: Native compiler reports error CS1980 for each syntax node which binds to dynamic type, we do the same by reporting a diagnostic here. // However, this means we generate multiple duplicate diagnostics, when a single one would suffice. // We may want to consider adding an "Unreported" flag to the DynamicTypeSymbol to suppress duplicate CS1980. // CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference? var info = new CSDiagnosticInfo(ErrorCode.ERR_DynamicAttributeMissing, AttributeDescription.DynamicAttribute.FullName); Symbol.ReportUseSiteDiagnostic(info, diagnostics, node.Location); } else { diagnostics.AddRange(bag); } bag.Free(); this.GetSpecialType(SpecialType.System_Boolean, diagnostics, node); } } // Gets the name lookup options for simple generic or non-generic name. private static LookupOptions GetSimpleNameLookupOptions(NameSyntax node, bool isVerbatimIdentifier) { if (SyntaxFacts.IsAttributeName(node)) { // SPEC: By convention, attribute classes are named with a suffix of Attribute. // SPEC: An attribute-name of the form type-name may either include or omit this suffix. // SPEC: If an attribute class is found both with and without this suffix, an ambiguity // SPEC: is present, and a compile-time error results. If the attribute-name is spelled // SPEC: such that its right-most identifier is a verbatim identifier (§2.4.2), then only // SPEC: an attribute without a suffix is matched, thus enabling such an ambiguity to be resolved. return isVerbatimIdentifier ? LookupOptions.VerbatimNameAttributeTypeOnly : LookupOptions.AttributeTypeOnly; } else { return LookupOptions.NamespacesOrTypesOnly; } } private static Symbol UnwrapAliasNoDiagnostics(Symbol symbol, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.Kind == SymbolKind.Alias) { return ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { AliasSymbol discarded; return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out discarded, diagnostics, syntax, basesBeingResolved)); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out alias, diagnostics, syntax, basesBeingResolved)); } alias = null; return symbol; } private Symbol UnwrapAlias(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { AliasSymbol discarded; return UnwrapAlias(symbol, out discarded, diagnostics, syntax, basesBeingResolved); } private Symbol UnwrapAlias(Symbol symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(syntax != null); Debug.Assert(diagnostics != null); if (symbol.Kind == SymbolKind.Alias) { alias = (AliasSymbol)symbol; var result = alias.GetAliasTarget(basesBeingResolved); var type = result as TypeSymbol; if ((object)type != null) { // pass args in a value tuple to avoid allocating a closure var args = (this, diagnostics, syntax); type.VisitType((typePart, argTuple, isNested) => { argTuple.Item1.ReportDiagnosticsIfObsolete(argTuple.diagnostics, typePart, argTuple.syntax, hasBaseReceiver: false); return false; }, args); } return result; } alias = null; return symbol; } private TypeWithAnnotations BindGenericSimpleNamespaceOrTypeOrAliasSymbol( GenericNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt) { // We are looking for a namespace, alias or type name and the user has given // us an identifier followed by a type argument list. Therefore they // must expect the result to be a generic type, and not a namespace or alias. // The result of this method will therefore always be a type symbol of the // correct arity, though it might have to be an error type. // We might be asked to bind a generic simple name of the form "T<,,,>", // which is only legal in the context of "typeof(T<,,,>)". If we are given // no type arguments and we are not in such a context, we'll give an error. // If we do have type arguments, then the result of this method will always // be a generic type symbol constructed with the given type arguments. // There are a number of possible error conditions. First, errors involving lookup: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // Second, we could be asked to resolve an unbound type T<,,,> when // not in a context where it is legal to do so. Note that this is // intended an improvement over the analysis performed by the // native compiler; in the native compiler we catch bad uses of unbound // types at parse time, not at semantic analysis time. That means that // we end up giving confusing "unexpected comma" or "expected type" // errors when it would be more informative to the user to simply // tell them that an unbound type is not legal in this position. // // This also means that we can get semantic analysis of the open // type in the IDE even in what would have been a syntax error case // in the native compiler. // // We need a heuristic to deal with the situation where both kinds of errors // are potentially in play: what if someone says "typeof(Bogus<>.Blah<int>)"? // There are two errors there: first, that Bogus is not found, not a type, // or not of the appropriate arity, and second, that it is illegal to make // a partially unbound type. // // The heuristic we will use is that the former kind of error takes priority // over the latter; if the meaning of "Bogus<>" cannot be successfully // determined then there is no point telling the user that in addition, // it is syntactically wrong. Moreover, at this point we do not know what they // mean by the remainder ".Blah<int>" of the expression and so it seems wrong to // deduce more errors from it. var plainName = node.Identifier.ValueText; SeparatedSyntaxList<TypeSyntax> typeArguments = node.TypeArgumentList.Arguments; bool isUnboundTypeExpr = node.IsUnboundGenericName; LookupOptions options = GetSimpleNameLookupOptions(node, isVerbatimIdentifier: false); NamedTypeSymbol unconstructedType = LookupGenericTypeName( diagnostics, basesBeingResolved, qualifierOpt, node, plainName, node.Arity, options); NamedTypeSymbol resultType; if (isUnboundTypeExpr) { if (!IsUnboundTypeAllowed(node)) { // If we already have an error type then skip reporting that the unbound type is illegal. if (!unconstructedType.IsErrorType()) { // error CS7003: Unexpected use of an unbound generic name diagnostics.Add(ErrorCode.ERR_UnexpectedUnboundGenericName, node.Location); } resultType = unconstructedType.Construct( UnboundArgumentErrorTypeSymbol.CreateTypeArguments( unconstructedType.TypeParameters, node.Arity, errorInfo: null), unbound: false); } else { resultType = unconstructedType.AsUnboundGenericType(); } } else if ((Flags & BinderFlags.SuppressTypeArgumentBinding) != 0) { resultType = unconstructedType.Construct(PlaceholderTypeArgumentSymbol.CreateTypeArguments(unconstructedType.TypeParameters)); } else { // It's not an unbound type expression, so we must have type arguments, and we have a // generic type of the correct arity in hand (possibly an error type). Bind the type // arguments and construct the final result. resultType = ConstructNamedType( unconstructedType, node, typeArguments, BindTypeArguments(typeArguments, diagnostics, basesBeingResolved), basesBeingResolved, diagnostics); } if (options.IsAttributeTypeLookup()) { // Generic type cannot be an attribute type. // Parser error has already been reported, just wrap the result type with error type symbol. Debug.Assert(unconstructedType.IsErrorType()); Debug.Assert(resultType.IsErrorType()); resultType = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(resultType), resultType, LookupResultKind.NotAnAttributeType, errorInfo: null); } return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(node.TypeArgumentList.GreaterThanToken), resultType); } private NamedTypeSymbol LookupGenericTypeName( BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt, GenericNameSyntax node, string plainName, int arity, LookupOptions options) { var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, plainName, arity, diagnostics); if ((object)errorResult != null) { return errorResult; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(lookupResult, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool wasError; Symbol lookupResultSymbol = ResultSymbol(lookupResult, plainName, arity, node, diagnostics, (basesBeingResolved != null), out wasError, qualifierOpt, options); // As we said in the method above, there are three cases here: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // In the first two cases we will be given back an error type symbol of the appropriate arity. // In the third case we will be given back the symbol -- say, a local variable symbol. // // In all three cases the appropriate error has already been reported. (That the // type was not found, that the generic type found does not have that arity, that // the non-generic type found cannot be used with a type argument list, or that // the symbol found is not something that takes type arguments. ) // The first thing to do is to make sure that we have some sort of generic type in hand. // (Note that an error type symbol is always a generic type.) NamedTypeSymbol type = lookupResultSymbol as NamedTypeSymbol; if ((object)type == null) { // We did a lookup with a generic arity, filtered to types and namespaces. If // we got back something other than a type, there had better be an error info // for us. Debug.Assert(lookupResult.Error != null); type = new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(lookupResultSymbol), ImmutableArray.Create<Symbol>(lookupResultSymbol), lookupResult.Kind, lookupResult.Error, arity); } lookupResult.Free(); return type; } private ExtendedErrorTypeSymbol CreateErrorIfLookupOnTypeParameter( CSharpSyntaxNode node, NamespaceOrTypeSymbol qualifierOpt, string name, int arity, BindingDiagnosticBag diagnostics) { if (((object)qualifierOpt != null) && (qualifierOpt.Kind == SymbolKind.TypeParameter)) { var diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_LookupInTypeVariable, qualifierOpt); diagnostics.Add(diagnosticInfo, node.Location); return new ExtendedErrorTypeSymbol(this.Compilation, name, arity, diagnosticInfo, unreported: false); } return null; } private ImmutableArray<TypeWithAnnotations> BindTypeArguments(SeparatedSyntaxList<TypeSyntax> typeArguments, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(typeArguments.Count > 0); var args = ArrayBuilder<TypeWithAnnotations>.GetInstance(); foreach (var argSyntax in typeArguments) { args.Add(BindTypeArgument(argSyntax, diagnostics, basesBeingResolved)); } return args.ToImmutableAndFree(); } private TypeWithAnnotations BindTypeArgument(TypeSyntax typeArgument, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { // Unsafe types can never be type arguments, but there's a special error code for that. var binder = this.WithAdditionalFlags(BinderFlags.SuppressUnsafeDiagnostics); var arg = typeArgument.Kind() == SyntaxKind.OmittedTypeArgument ? TypeWithAnnotations.Create(UnboundArgumentErrorTypeSymbol.Instance) : binder.BindType(typeArgument, diagnostics, basesBeingResolved); return arg; } /// <remarks> /// Keep check and error in sync with ConstructBoundMethodGroupAndReportOmittedTypeArguments. /// </remarks> private NamedTypeSymbol ConstructNamedTypeUnlessTypeArgumentOmitted(SyntaxNode typeSyntax, NamedTypeSymbol type, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BindingDiagnosticBag diagnostics) { if (typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, typeSyntax, type, MessageID.IDS_SK_TYPE.Localize(), typeArgumentsSyntax.Count); // If the syntax looks like an unbound generic type, then they probably wanted the definition. // Give an error indicating that the syntax is incorrect and then use the definition. // CONSIDER: we could construct an unbound generic type symbol, but that would probably be confusing // outside a typeof. return type; } else { // we pass an empty basesBeingResolved here because this invocation is not on any possible path of // infinite recursion in binding base clauses. return ConstructNamedType(type, typeSyntax, typeArgumentsSyntax, typeArguments, basesBeingResolved: null, diagnostics: diagnostics); } } /// <remarks> /// Keep check and error in sync with ConstructNamedTypeUnlessTypeArgumentOmitted. /// </remarks> private static BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedTypeArguments( SyntaxNode syntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BoundExpression receiver, string plainName, ArrayBuilder<Symbol> members, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, bool hasErrors, BindingDiagnosticBag diagnostics) { if (!hasErrors && lookupResult.IsMultiViable && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, syntax, plainName, MessageID.IDS_MethodGroup.Localize(), typeArgumentsSyntax.Count); hasErrors = true; } Debug.Assert(members.Count > 0); switch (members[0].Kind) { case SymbolKind.Method: return new BoundMethodGroup( syntax, typeArguments, receiver, plainName, members.SelectAsArray(s_toMethodSymbolFunc), lookupResult, methodGroupFlags, hasErrors); case SymbolKind.Property: return new BoundPropertyGroup( syntax, members.SelectAsArray(s_toPropertySymbolFunc), receiver, lookupResult.Kind, hasErrors); default: throw ExceptionUtilities.UnexpectedValue(members[0].Kind); } } private static readonly Func<Symbol, MethodSymbol> s_toMethodSymbolFunc = s => (MethodSymbol)s; private static readonly Func<Symbol, PropertySymbol> s_toPropertySymbolFunc = s => (PropertySymbol)s; private NamedTypeSymbol ConstructNamedType( NamedTypeSymbol type, SyntaxNode typeSyntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics) { Debug.Assert(!typeArguments.IsEmpty); type = type.Construct(typeArguments); if (ShouldCheckConstraints && ConstraintsHelper.RequiresChecking(type)) { bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); type.CheckConstraintsForNamedType(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability, typeSyntax.Location, diagnostics), typeSyntax, typeArgumentsSyntax, basesBeingResolved); } return type; } /// <summary> /// Check generic type constraints unless the type is used as part of a type or method /// declaration. In those cases, constraints checking is handled by the caller. /// </summary> private bool ShouldCheckConstraints { get { return !this.Flags.Includes(BinderFlags.SuppressConstraintChecks); } } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindQualifiedName( ExpressionSyntax leftName, SimpleNameSyntax rightName, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var left = BindNamespaceOrTypeSymbol(leftName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics: false).NamespaceOrTypeSymbol; ReportDiagnosticsIfObsolete(diagnostics, left, leftName, hasBaseReceiver: false); bool isLeftUnboundGenericType = left.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)left).IsUnboundGenericType; if (isLeftUnboundGenericType) { // If left name bound to an unbound generic type, // we want to perform right name lookup within // left's original named type definition. left = ((NamedTypeSymbol)left).OriginalDefinition; } // since the name is qualified, it cannot result in a using alias symbol, only a type or namespace var right = this.BindSimpleNamespaceOrTypeOrAliasSymbol(rightName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); // If left name bound to an unbound generic type // and right name bound to a generic type, we must // convert right to an unbound generic type. if (isLeftUnboundGenericType) { return convertToUnboundGenericType(); } return right; // This part is moved into a local function to reduce the method's stack frame size NamespaceOrTypeOrAliasSymbolWithAnnotations convertToUnboundGenericType() { var namedTypeRight = right.Symbol as NamedTypeSymbol; if ((object)namedTypeRight != null && namedTypeRight.IsGenericType) { TypeWithAnnotations type = right.TypeWithAnnotations; return type.WithTypeAndModifiers(namedTypeRight.AsUnboundGenericType(), type.CustomModifiers); } return right; } } internal NamedTypeSymbol GetSpecialType(SpecialType typeId, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetSpecialType(this.Compilation, typeId, node, diagnostics); } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, SyntaxNode node, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, node); return typeSymbol; } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, Location location, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the special /// member isn't found. /// </summary> internal Symbol GetSpecialTypeMember(SpecialMember member, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { Symbol memberSymbol; return TryGetSpecialTypeMember(this.Compilation, member, syntax, diagnostics, out memberSymbol) ? memberSymbol : null; } internal static bool TryGetSpecialTypeMember<TSymbol>(CSharpCompilation compilation, SpecialMember specialMember, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out TSymbol symbol) where TSymbol : Symbol { symbol = (TSymbol)compilation.GetSpecialTypeMember(specialMember); if ((object)symbol == null) { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, syntax.Location, descriptor.DeclaringTypeMetadataName, descriptor.Name); return false; } var useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(symbol); if (useSiteInfo.DiagnosticInfo != null) { diagnostics.ReportUseSiteDiagnostic(useSiteInfo.DiagnosticInfo, new SourceLocation(syntax)); } // No need to track assemblies used by special members or types. They are coming from core library, which // doesn't have any dependencies. return true; } private static UseSiteInfo<AssemblySymbol> GetUseSiteInfoForWellKnownMemberOrContainingType(Symbol symbol) { Debug.Assert(symbol.IsDefinition); UseSiteInfo<AssemblySymbol> info = symbol.GetUseSiteInfo(); symbol.MergeUseSiteInfo(ref info, symbol.ContainingType.GetUseSiteInfo()); return info; } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode node) { return diagnostics.ReportUseSite(symbol, node); } internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxToken token) { return diagnostics.ReportUseSite(symbol, token); } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, Location location) { return diagnostics.ReportUseSite(symbol, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(type, diagnostics, node.Location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { return GetWellKnownType(this.Compilation, type, diagnostics, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(compilation, type, diagnostics, node.Location); } internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { NamedTypeSymbol typeSymbol = compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { NamedTypeSymbol typeSymbol = this.Compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); typeSymbol.AddUseSiteInfo(ref useSiteInfo); return typeSymbol; } internal Symbol GetWellKnownTypeMember(WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { return GetWellKnownTypeMember(Compilation, member, diagnostics, location, syntax, isOptional); } /// <summary> /// Retrieves a well-known type member and reports diagnostics. /// </summary> /// <returns>Null if the symbol is missing.</returns> internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { Debug.Assert((syntax != null) ^ (location != null)); UseSiteInfo<AssemblySymbol> useSiteInfo; Symbol memberSymbol = GetWellKnownTypeMember(compilation, member, out useSiteInfo, isOptional); diagnostics.Add(useSiteInfo, location ?? syntax.Location); return memberSymbol; } internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, out UseSiteInfo<AssemblySymbol> useSiteInfo, bool isOptional = false) { Symbol memberSymbol = compilation.GetWellKnownTypeMember(member); if ((object)memberSymbol != null) { useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(memberSymbol); if (useSiteInfo.DiagnosticInfo != null) { // Dev11 reports use-site diagnostics even for optional symbols that are found. // We decided to silently ignore bad optional symbols. // Report errors only for non-optional members: if (isOptional) { var severity = useSiteInfo.DiagnosticInfo.Severity; // if the member is optional and bad for whatever reason ignore it: if (severity == DiagnosticSeverity.Error) { useSiteInfo = default; return null; } // ignore warnings: useSiteInfo = new UseSiteInfo<AssemblySymbol>(diagnosticInfo: null, useSiteInfo.PrimaryDependency, useSiteInfo.SecondaryDependencies); } } } else if (!isOptional) { // member is missing MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member); useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name)); } else { useSiteInfo = default; } return memberSymbol; } private class ConsistentSymbolOrder : IComparer<Symbol> { public static readonly ConsistentSymbolOrder Instance = new ConsistentSymbolOrder(); public int Compare(Symbol fst, Symbol snd) { if (snd == fst) return 0; if ((object)fst == null) return -1; if ((object)snd == null) return 1; if (snd.Name != fst.Name) return string.CompareOrdinal(fst.Name, snd.Name); if (snd.Kind != fst.Kind) return (int)fst.Kind - (int)snd.Kind; int aLocationsCount = !snd.Locations.IsDefault ? snd.Locations.Length : 0; int bLocationsCount = fst.Locations.Length; if (aLocationsCount != bLocationsCount) return aLocationsCount - bLocationsCount; if (aLocationsCount == 0 && bLocationsCount == 0) return Compare(fst.ContainingSymbol, snd.ContainingSymbol); Location la = snd.Locations[0]; Location lb = fst.Locations[0]; if (la.IsInSource != lb.IsInSource) return la.IsInSource ? 1 : -1; int containerResult = Compare(fst.ContainingSymbol, snd.ContainingSymbol); if (!la.IsInSource) return containerResult; if (containerResult == 0 && la.SourceTree == lb.SourceTree) return lb.SourceSpan.Start - la.SourceSpan.Start; return containerResult; } } // return the type or namespace symbol in a lookup result, or report an error. internal Symbol ResultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options = default(LookupOptions)) { Symbol symbol = resultSymbol(result, simpleName, arity, where, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (symbol.Kind == SymbolKind.NamedType) { CheckReceiverAndRuntimeSupportForSymbolAccess(where, receiverOpt: null, symbol, diagnostics); if (suppressUseSiteDiagnostics && diagnostics.DependenciesBag is object) { AssemblySymbol container = symbol.ContainingAssembly; if (container is object && container != Compilation.Assembly && container != Compilation.Assembly.CorLibrary) { diagnostics.AddDependency(container); } } } return symbol; Symbol resultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { Debug.Assert(where != null); Debug.Assert(diagnostics != null); var symbols = result.Symbols; wasError = false; if (result.IsMultiViable) { if (symbols.Count > 1) { // gracefully handle symbols.Count > 2 symbols.Sort(ConsistentSymbolOrder.Instance); var originalSymbols = symbols.ToImmutable(); for (int i = 0; i < symbols.Count; i++) { symbols[i] = UnwrapAlias(symbols[i], diagnostics, where); } BestSymbolInfo secondBest; BestSymbolInfo best = GetBestSymbolInfo(symbols, out secondBest); Debug.Assert(!best.IsNone); Debug.Assert(!secondBest.IsNone); if (best.IsFromCompilation && !secondBest.IsFromCompilation) { var srcSymbol = symbols[best.Index]; var mdSymbol = symbols[secondBest.Index]; object arg0; if (best.IsFromSourceModule) { arg0 = srcSymbol.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = srcSymbol.ContainingModule; } //if names match, arities match, and containing symbols match (recursively), ... if (NameAndArityMatchRecursively(srcSymbol, mdSymbol)) { if (srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.NamedType) { // ErrorCode.WRN_SameFullNameThisNsAgg: The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisNsAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.Namespace) { // ErrorCode.WRN_SameFullNameThisAggNs: The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggNs, where.Location, originalSymbols, arg0, srcSymbol, GetContainingAssembly(mdSymbol), mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.NamedType) { // WRN_SameFullNameThisAggAgg: The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else { // namespace would be merged with the source namespace: Debug.Assert(!(srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.Namespace)); } } } var first = symbols[best.Index]; var second = symbols[secondBest.Index]; Debug.Assert(!Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything) || options.IsAttributeTypeLookup(), "This kind of ambiguity is only possible for attributes."); Debug.Assert(!Symbol.Equals(first, second, TypeCompareKind.ConsiderEverything) || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why does the LookupResult contain the same symbol twice?"); CSDiagnosticInfo info; bool reportError; //if names match, arities match, and containing symbols match (recursively), ... if (first != second && NameAndArityMatchRecursively(first, second)) { // suppress reporting the error if we found multiple symbols from source module // since an error has already been reported from the declaration reportError = !(best.IsFromSourceModule && secondBest.IsFromSourceModule); if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType) { if (first.OriginalDefinition == second.OriginalDefinition) { // We imported different generic instantiations of the same generic type // and have an ambiguous reference to a type nested in it reportError = true; // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } else { Debug.Assert(!best.IsFromCorLibrary); // ErrorCode.ERR_SameFullNameAggAgg: The type '{1}' exists in both '{0}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameAggAgg, originalSymbols, new object[] { first.ContainingAssembly, first, second.ContainingAssembly }); // Do not report this error if the first is declared in source and the second is declared in added module, // we already reported declaration error about this name collision. // Do not report this error if both are declared in added modules, // we will report assembly level declaration error about this name collision. if (secondBest.IsFromAddedModule) { Debug.Assert(best.IsFromCompilation); reportError = false; } else if (this.Flags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes) && secondBest.IsFromCorLibrary) { // Ignore duplicate types from the cor library if necessary. // (Specifically the framework assemblies loaded at runtime in // the EE may contain types also available from mscorlib.dll.) return first; } } } else if (first.Kind == SymbolKind.Namespace && second.Kind == SymbolKind.NamedType) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(first), first, second.ContainingAssembly, second }); // Do not report this error if namespace is declared in source and the type is declared in added module, // we already reported declaration error about this name collision. if (best.IsFromSourceModule && secondBest.IsFromAddedModule) { reportError = false; } } else if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.Namespace) { if (!secondBest.IsFromCompilation || secondBest.IsFromSourceModule) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(second), second, first.ContainingAssembly, first }); } else { Debug.Assert(secondBest.IsFromAddedModule); // ErrorCode.ERR_SameFullNameThisAggThisNs: The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}' object arg0; if (best.IsFromSourceModule) { arg0 = first.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = first.ContainingModule; } ModuleSymbol arg2 = second.ContainingModule; // Merged namespaces that span multiple modules don't have a containing module, // so just use module with the smallest ordinal from the containing assembly. if ((object)arg2 == null) { foreach (NamespaceSymbol ns in ((NamespaceSymbol)second).ConstituentNamespaces) { if (ns.ContainingAssembly == Compilation.Assembly) { ModuleSymbol module = ns.ContainingModule; if ((object)arg2 == null || arg2.Ordinal > module.Ordinal) { arg2 = module; } } } } Debug.Assert(arg2.ContainingAssembly == Compilation.Assembly); info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameThisAggThisNs, originalSymbols, new object[] { arg0, first, arg2, second }); } } else if (first.Kind == SymbolKind.RangeVariable && second.Kind == SymbolKind.RangeVariable) { // We will already have reported a conflicting range variable declaration. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } else { // TODO: this is not an appropriate error message here, but used as a fallback until the // appropriate diagnostics are implemented. // '{0}' is an ambiguous reference between '{1}' and '{2}' //info = diagnostics.Add(ErrorCode.ERR_AmbigContext, location, readOnlySymbols, // whereText, // first, // second); // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); reportError = true; } } else { Debug.Assert(originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why was the lookup result viable if it contained non-equal symbols with the same name?"); reportError = true; if (first is NamespaceOrTypeSymbol && second is NamespaceOrTypeSymbol) { if (options.IsAttributeTypeLookup() && first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType && originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name && // Use alias names, if available. Compilation.IsAttributeType((NamedTypeSymbol)first) && Compilation.IsAttributeType((NamedTypeSymbol)second)) { // SPEC: If an attribute class is found both with and without Attribute suffix, an ambiguity // SPEC: is present, and a compile-time error results. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbiguousAttribute, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, first, second }); } else { // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } } else { // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } } wasError = true; if (reportError) { diagnostics.Add(info, where.Location); } return new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(originalSymbols[0]), originalSymbols, LookupResultKind.Ambiguous, info, arity); } else { // Single viable result. var singleResult = symbols[0]; // Cannot reference System.Void directly. var singleType = singleResult as TypeSymbol; if ((object)singleType != null && singleType.PrimitiveTypeCode == Cci.PrimitiveTypeCode.Void && simpleName == "Void") { wasError = true; var errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_SystemVoid); diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(singleResult), singleResult, LookupResultKind.NotReferencable, errorInfo); // UNDONE: Review resultkind. } // Check for bad symbol. else { if (singleResult.Kind == SymbolKind.NamedType && ((SourceModuleSymbol)this.Compilation.SourceModule).AnyReferencedAssembliesAreLinked) { // Complain about unembeddable types from linked assemblies. if (diagnostics.DiagnosticBag is object) { Emit.NoPia.EmbeddedTypesManager.IsValidEmbeddableType((NamedTypeSymbol)singleResult, where, diagnostics.DiagnosticBag); } } if (!suppressUseSiteDiagnostics) { wasError = ReportUseSite(singleResult, diagnostics, where); } else if (singleResult.Kind == SymbolKind.ErrorType) { // We want to report ERR_CircularBase error on the spot to make sure // that the right location is used for it. var errorType = (ErrorTypeSymbol)singleResult; if (errorType.Unreported) { DiagnosticInfo errorInfo = errorType.ErrorInfo; if (errorInfo != null && errorInfo.Code == (int)ErrorCode.ERR_CircularBase) { wasError = true; diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(errorType), errorType.Name, errorType.Arity, errorInfo, unreported: false); } } } } return singleResult; } } // Below here is the error case; no viable symbols found (but maybe one or more non-viable.) wasError = true; if (result.Kind == LookupResultKind.Empty) { string aliasOpt = null; SyntaxNode node = where; while (node is ExpressionSyntax) { if (node.Kind() == SyntaxKind.AliasQualifiedName) { aliasOpt = ((AliasQualifiedNameSyntax)node).Alias.Identifier.ValueText; break; } node = node.Parent; } CSDiagnosticInfo info = NotFound(where, simpleName, arity, (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, diagnostics, aliasOpt, qualifierOpt, options); return new ExtendedErrorTypeSymbol(qualifierOpt ?? Compilation.Assembly.GlobalNamespace, simpleName, arity, info); } Debug.Assert(symbols.Count > 0); // Report any errors we encountered with the symbol we looked up. if (!suppressUseSiteDiagnostics) { for (int i = 0; i < symbols.Count; i++) { ReportUseSite(symbols[i], diagnostics, where); } } // result.Error might be null if we have already generated parser errors, // e.g. when generic name is used for attribute name. if (result.Error != null && ((object)qualifierOpt == null || qualifierOpt.Kind != SymbolKind.ErrorType)) // Suppress cascading. { diagnostics.Add(new CSDiagnostic(result.Error, where.Location)); } if ((symbols.Count > 1) || (symbols[0] is NamespaceOrTypeSymbol || symbols[0] is AliasSymbol) || result.Kind == LookupResultKind.NotATypeOrNamespace || result.Kind == LookupResultKind.NotAnAttributeType) { // Bad type or namespace (or things expected as types/namespaces) are packaged up as error types, preserving the symbols and the result kind. // We do this if there are multiple symbols too, because just returning one would be losing important information, and they might // be of different kinds. return new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), result.Kind, result.Error, arity); } else { // It's a single non-type-or-namespace; error was already reported, so just return it. return symbols[0]; } } } private static AssemblySymbol GetContainingAssembly(Symbol symbol) { // Merged namespaces that span multiple assemblies don't have a containing assembly, // so just use the containing assembly of the first constituent. return symbol.ContainingAssembly ?? ((NamespaceSymbol)symbol).ConstituentNamespaces.First().ContainingAssembly; } [Flags] private enum BestSymbolLocation { None, FromSourceModule, FromAddedModule, FromReferencedAssembly, FromCorLibrary, } [DebuggerDisplay("Location = {_location}, Index = {_index}")] private struct BestSymbolInfo { private readonly BestSymbolLocation _location; private readonly int _index; /// <summary> /// Returns -1 if None. /// </summary> public int Index { get { return IsNone ? -1 : _index; } } public bool IsFromSourceModule { get { return _location == BestSymbolLocation.FromSourceModule; } } public bool IsFromAddedModule { get { return _location == BestSymbolLocation.FromAddedModule; } } public bool IsFromCompilation { get { return (_location == BestSymbolLocation.FromSourceModule) || (_location == BestSymbolLocation.FromAddedModule); } } public bool IsNone { get { return _location == BestSymbolLocation.None; } } public bool IsFromCorLibrary { get { return _location == BestSymbolLocation.FromCorLibrary; } } public BestSymbolInfo(BestSymbolLocation location, int index) { Debug.Assert(location != BestSymbolLocation.None); _location = location; _index = index; } /// <summary> /// Prefers symbols from source module, then from added modules, then from referenced assemblies. /// Returns true if values were swapped. /// </summary> public static bool Sort(ref BestSymbolInfo first, ref BestSymbolInfo second) { if (IsSecondLocationBetter(first._location, second._location)) { BestSymbolInfo temp = first; first = second; second = temp; return true; } return false; } /// <summary> /// Returns true if the second is a better location than the first. /// </summary> public static bool IsSecondLocationBetter(BestSymbolLocation firstLocation, BestSymbolLocation secondLocation) { Debug.Assert(secondLocation != 0); return (firstLocation == BestSymbolLocation.None) || (firstLocation > secondLocation); } } /// <summary> /// Prefer symbols from source module, then from added modules, then from referenced assemblies. /// </summary> private BestSymbolInfo GetBestSymbolInfo(ArrayBuilder<Symbol> symbols, out BestSymbolInfo secondBest) { BestSymbolInfo first = default(BestSymbolInfo); BestSymbolInfo second = default(BestSymbolInfo); var compilation = this.Compilation; for (int i = 0; i < symbols.Count; i++) { var symbol = symbols[i]; BestSymbolLocation location; if (symbol.Kind == SymbolKind.Namespace) { location = BestSymbolLocation.None; foreach (var ns in ((NamespaceSymbol)symbol).ConstituentNamespaces) { var current = GetLocation(compilation, ns); if (BestSymbolInfo.IsSecondLocationBetter(location, current)) { location = current; if (location == BestSymbolLocation.FromSourceModule) { break; } } } } else { location = GetLocation(compilation, symbol); } var third = new BestSymbolInfo(location, i); if (BestSymbolInfo.Sort(ref second, ref third)) { BestSymbolInfo.Sort(ref first, ref second); } } Debug.Assert(!first.IsNone); Debug.Assert(!second.IsNone); secondBest = second; return first; } private static BestSymbolLocation GetLocation(CSharpCompilation compilation, Symbol symbol) { var containingAssembly = symbol.ContainingAssembly; if (containingAssembly == compilation.SourceAssembly) { return (symbol.ContainingModule == compilation.SourceModule) ? BestSymbolLocation.FromSourceModule : BestSymbolLocation.FromAddedModule; } else { return (containingAssembly == containingAssembly.CorLibrary) ? BestSymbolLocation.FromCorLibrary : BestSymbolLocation.FromReferencedAssembly; } } /// <remarks> /// This is only intended to be called when the type isn't found (i.e. not when it is found but is inaccessible, has the wrong arity, etc). /// </remarks> private CSDiagnosticInfo NotFound(SyntaxNode where, string simpleName, int arity, string whereText, BindingDiagnosticBag diagnostics, string aliasOpt, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { var location = where.Location; // Lookup totally ignores type forwarders, but we want the type lookup diagnostics // to distinguish between a type that can't be found and a type that is only present // as a type forwarder. We'll look for type forwarders in the containing and // referenced assemblies and report more specific diagnostics if they are found. AssemblySymbol forwardedToAssembly; // for attributes, suggest both, but not for verbatim name if (options.IsAttributeTypeLookup() && !options.IsVerbatimNameAttributeTypeLookup()) { // just recurse one level, so cheat and OR verbatim name option :) NotFound(where, simpleName, arity, whereText + "Attribute", diagnostics, aliasOpt, qualifierOpt, options | LookupOptions.VerbatimNameAttributeTypeOnly); } if ((object)qualifierOpt != null) { if (qualifierOpt.IsType) { var errorQualifier = qualifierOpt as ErrorTypeSymbol; if ((object)errorQualifier != null && errorQualifier.ErrorInfo != null) { return (CSDiagnosticInfo)errorQualifier.ErrorInfo; } return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, location, whereText, qualifierOpt); } else { Debug.Assert(qualifierOpt.IsNamespace); forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if (ReferenceEquals(qualifierOpt, Compilation.GlobalNamespace)) { Debug.Assert(aliasOpt == null || aliasOpt == SyntaxFacts.GetText(SyntaxKind.GlobalKeyword)); return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFound, location, whereText, qualifierOpt) : diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly); } else { object container = qualifierOpt; // If there was an alias (e.g. A::C) and the given qualifier is the global namespace of the alias, // then use the alias name in the error message, since it's more helpful than "<global namespace>". if (aliasOpt != null && qualifierOpt.IsNamespace && ((NamespaceSymbol)qualifierOpt).IsGlobalNamespace) { container = aliasOpt; } return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNS, location, whereText, container) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, container, forwardedToAssembly); } } } if (options == LookupOptions.NamespaceAliasesOnly) { return diagnostics.Add(ErrorCode.ERR_AliasNotFound, location, whereText); } if ((where as IdentifierNameSyntax)?.Identifier.Text == "var" && !options.IsAttributeTypeLookup()) { var code = (where.Parent is QueryClauseSyntax) ? ErrorCode.ERR_TypeVarNotFoundRangeVariable : ErrorCode.ERR_TypeVarNotFound; return diagnostics.Add(code, location); } forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if ((object)forwardedToAssembly != null) { return qualifierOpt == null ? diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, qualifierOpt, forwardedToAssembly); } return diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFound, location, whereText); } protected virtual AssemblySymbol GetForwardedToAssemblyInUsingNamespaces(string metadataName, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { return Next?.GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } protected AssemblySymbol GetForwardedToAssembly(string fullName, BindingDiagnosticBag diagnostics, Location location) { var metadataName = MetadataTypeName.FromFullName(fullName); foreach (var referencedAssembly in Compilation.Assembly.Modules[0].GetReferencedAssemblySymbols()) { var forwardedType = referencedAssembly.TryLookupForwardedMetadataType(ref metadataName); if ((object)forwardedType != null) { if (forwardedType.Kind == SymbolKind.ErrorType) { DiagnosticInfo diagInfo = ((ErrorTypeSymbol)forwardedType).ErrorInfo; if (diagInfo.Code == (int)ErrorCode.ERR_CycleInTypeForwarder) { Debug.Assert((object)forwardedType.ContainingAssembly != null, "How did we find a cycle if there was no forwarding?"); diagnostics.Add(ErrorCode.ERR_CycleInTypeForwarder, location, fullName, forwardedType.ContainingAssembly.Name); } else if (diagInfo.Code == (int)ErrorCode.ERR_TypeForwardedToMultipleAssemblies) { diagnostics.Add(diagInfo, location); return null; // Cannot determine a suitable forwarding assembly } } return forwardedType.ContainingAssembly; } } return null; } /// <summary> /// Look for a type forwarder for the given type in the containing assembly and any referenced assemblies. /// </summary> /// <param name="name">The name of the (potentially) forwarded type.</param> /// <param name="arity">The arity of the forwarded type.</param> /// <param name="qualifierOpt">The namespace of the potentially forwarded type. If none is provided, will /// try Usings of the current import for eligible namespaces and return the namespace of the found forwarder, /// if any.</param> /// <param name="diagnostics">Will be used to report non-fatal errors during look up.</param> /// <param name="location">Location to report errors on.</param> /// <returns>Returns the Assembly to which the type is forwarded, or null if none is found.</returns> /// <remarks> /// Since this method is intended to be used for error reporting, it stops as soon as it finds /// any type forwarder (or an error to report). It does not check other assemblies for consistency or better results. /// </remarks> protected AssemblySymbol GetForwardedToAssembly(string name, int arity, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { // If we are in the process of binding assembly level attributes, we might get into an infinite cycle // if any of the referenced assemblies forwards type to this assembly. Since forwarded types // are specified through assembly level attributes, an attempt to resolve the forwarded type // might require us to examine types forwarded by this assembly, thus binding assembly level // attributes again. And the cycle continues. // So, we won't do the analysis in this case, at the expense of better diagnostics. if ((this.Flags & BinderFlags.InContextualAttributeBinder) != 0) { var current = this; do { var contextualAttributeBinder = current as ContextualAttributeBinder; if (contextualAttributeBinder != null) { if ((object)contextualAttributeBinder.AttributeTarget != null && contextualAttributeBinder.AttributeTarget.Kind == SymbolKind.Assembly) { return null; } break; } current = current.Next; } while (current != null); } // NOTE: This won't work if the type isn't using CLS-style generic naming (i.e. `arity), but this code is // only intended to improve diagnostic messages, so false negatives in corner cases aren't a big deal. var metadataName = MetadataHelpers.ComposeAritySuffixedMetadataName(name, arity); var fullMetadataName = MetadataHelpers.BuildQualifiedName(qualifierOpt?.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), metadataName); var result = GetForwardedToAssembly(fullMetadataName, diagnostics, location); if ((object)result != null) { return result; } if ((object)qualifierOpt == null) { return GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } return null; } #nullable enable internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, BindingDiagnosticBag diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, DiagnosticBag? diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax.SyntaxTree, feature, diagnostics, location ?? syntax.GetLocation()); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, BindingDiagnosticBag diagnostics, Location location) { return CheckFeatureAvailability(tree, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, DiagnosticBag? diagnostics, Location location) { if (feature.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)tree.Options) is { } diagInfo) { diagnostics?.Add(diagInfo, location); return false; } return true; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasic/LineCommit/BeforeCommitCaretMoveUndoPrimitive.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Friend Class BeforeCommitCaretMoveUndoPrimitive Inherits AbstractCommitCaretMoveUndoPrimitive Private ReadOnly _oldPosition As Integer Private ReadOnly _oldVirtualSpaces As Integer Private _active As Boolean Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, oldLocation As CaretPosition) MyBase.New(textBuffer, textBufferAssociatedViewService) ' Grab the old position and virtual spaces. This is cheaper than holding onto ' a VirtualSnapshotPoint as it won't hold old snapshots alive _oldPosition = oldLocation.VirtualBufferPosition.Position _oldVirtualSpaces = oldLocation.VirtualBufferPosition.VirtualSpaces End Sub Public Sub MarkAsActive() ' We must create this undo primitive and add it to the transaction before we know if our ' commit is actually going to do something. If we cancel the transaction, we still get ' called on Undo, but we don't want to actually do anything there. Thus we have flag to ' know if we're actually a live undo primitive _active = True End Sub Public Overrides Sub [Do]() ' When we are going forward, we do nothing here since the AfterCommitCaretMoveUndoPrimitive ' will take care of it End Sub Public Overrides Sub Undo() ' Sometimes we cancel the transaction, in this case don't do anything. If Not _active Then Return End If Dim view = TryGetView() If view IsNot Nothing Then view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _oldPosition), _oldVirtualSpaces)) view.Caret.EnsureVisible() 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 Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Friend Class BeforeCommitCaretMoveUndoPrimitive Inherits AbstractCommitCaretMoveUndoPrimitive Private ReadOnly _oldPosition As Integer Private ReadOnly _oldVirtualSpaces As Integer Private _active As Boolean Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, oldLocation As CaretPosition) MyBase.New(textBuffer, textBufferAssociatedViewService) ' Grab the old position and virtual spaces. This is cheaper than holding onto ' a VirtualSnapshotPoint as it won't hold old snapshots alive _oldPosition = oldLocation.VirtualBufferPosition.Position _oldVirtualSpaces = oldLocation.VirtualBufferPosition.VirtualSpaces End Sub Public Sub MarkAsActive() ' We must create this undo primitive and add it to the transaction before we know if our ' commit is actually going to do something. If we cancel the transaction, we still get ' called on Undo, but we don't want to actually do anything there. Thus we have flag to ' know if we're actually a live undo primitive _active = True End Sub Public Overrides Sub [Do]() ' When we are going forward, we do nothing here since the AfterCommitCaretMoveUndoPrimitive ' will take care of it End Sub Public Overrides Sub Undo() ' Sometimes we cancel the transaction, in this case don't do anything. If Not _active Then Return End If Dim view = TryGetView() If view IsNot Nothing Then view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _oldPosition), _oldVirtualSpaces)) view.Caret.EnsureVisible() End If End Sub End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/MSBuildTest/MSBuildWorkspaceTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTestBase : WorkspaceTestBase { protected const string MSBuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; protected static void AssertFailures(MSBuildWorkspace workspace, params string[] expectedFailures) { AssertEx.Equal(expectedFailures, workspace.Diagnostics.Where(d => d.Kind == WorkspaceDiagnosticKind.Failure).Select(d => d.Message)); } protected async Task AssertCSCompilationOptionsAsync<T>(T expected, Func<CS.CSharpCompilationOptions, T> actual) { var options = await LoadCSharpCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertCSParseOptionsAsync<T>(T expected, Func<CS.CSharpParseOptions, T> actual) { var options = await LoadCSharpParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBCompilationOptionsAsync<T>(T expected, Func<VB.VisualBasicCompilationOptions, T> actual) { var options = await LoadVisualBasicCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBParseOptionsAsync<T>(T expected, Func<VB.VisualBasicParseOptions, T> actual) { var options = await LoadVisualBasicParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task<CS.CSharpCompilationOptions> LoadCSharpCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpCompilationOptions)project.CompilationOptions; } } protected async Task<CS.CSharpParseOptions> LoadCSharpParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpParseOptions)project.ParseOptions; } } protected async Task<VB.VisualBasicCompilationOptions> LoadVisualBasicCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicCompilationOptions)project.CompilationOptions; } } protected async Task<VB.VisualBasicParseOptions> LoadVisualBasicParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicParseOptions)project.ParseOptions; } } protected static int GetMethodInsertionPoint(VB.Syntax.ClassBlockSyntax classBlock) { if (classBlock.Implements.Count > 0) { return classBlock.Implements[classBlock.Implements.Count - 1].FullSpan.End; } else if (classBlock.Inherits.Count > 0) { return classBlock.Inherits[classBlock.Inherits.Count - 1].FullSpan.End; } else { return classBlock.BlockStatement.FullSpan.End; } } protected async Task PrepareCrossLanguageProjectWithEmittedMetadataAsync() { // Now try variant of CSharpProject that has an emitted assembly CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ForEmittedOutput)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.NotNull(p1.OutputFilePath); Assert.Equal("EmittedCSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); // if the assembly doesn't already exist, emit it now if (!File.Exists(p1.OutputFilePath)) { var c1 = await p1.GetCompilationAsync(); var result = c1.Emit(p1.OutputFilePath); Assert.True(result.Success); } } } protected async Task<Solution> SolutionAsync(params IBuilder[] inputs) { var files = GetSolutionFiles(inputs); CreateFiles(files); var solutionFileName = files.First(t => t.fileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase)).fileName; solutionFileName = GetSolutionFileName(solutionFileName); using (var workspace = CreateMSBuildWorkspace()) { return await workspace.OpenSolutionAsync(solutionFileName); } } protected static MSBuildWorkspace CreateMSBuildWorkspace(params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties)); } protected static MSBuildWorkspace CreateMSBuildWorkspace(HostServices hostServices, params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties), hostServices); } private static Dictionary<string, string> CreateProperties((string key, string value)[] additionalProperties) { var properties = new Dictionary<string, string>(); foreach (var (k, v) in additionalProperties) { properties.Add(k, v); } return properties; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTestBase : WorkspaceTestBase { protected const string MSBuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; protected static void AssertFailures(MSBuildWorkspace workspace, params string[] expectedFailures) { AssertEx.Equal(expectedFailures, workspace.Diagnostics.Where(d => d.Kind == WorkspaceDiagnosticKind.Failure).Select(d => d.Message)); } protected async Task AssertCSCompilationOptionsAsync<T>(T expected, Func<CS.CSharpCompilationOptions, T> actual) { var options = await LoadCSharpCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertCSParseOptionsAsync<T>(T expected, Func<CS.CSharpParseOptions, T> actual) { var options = await LoadCSharpParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBCompilationOptionsAsync<T>(T expected, Func<VB.VisualBasicCompilationOptions, T> actual) { var options = await LoadVisualBasicCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBParseOptionsAsync<T>(T expected, Func<VB.VisualBasicParseOptions, T> actual) { var options = await LoadVisualBasicParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task<CS.CSharpCompilationOptions> LoadCSharpCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpCompilationOptions)project.CompilationOptions; } } protected async Task<CS.CSharpParseOptions> LoadCSharpParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpParseOptions)project.ParseOptions; } } protected async Task<VB.VisualBasicCompilationOptions> LoadVisualBasicCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicCompilationOptions)project.CompilationOptions; } } protected async Task<VB.VisualBasicParseOptions> LoadVisualBasicParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicParseOptions)project.ParseOptions; } } protected static int GetMethodInsertionPoint(VB.Syntax.ClassBlockSyntax classBlock) { if (classBlock.Implements.Count > 0) { return classBlock.Implements[classBlock.Implements.Count - 1].FullSpan.End; } else if (classBlock.Inherits.Count > 0) { return classBlock.Inherits[classBlock.Inherits.Count - 1].FullSpan.End; } else { return classBlock.BlockStatement.FullSpan.End; } } protected async Task PrepareCrossLanguageProjectWithEmittedMetadataAsync() { // Now try variant of CSharpProject that has an emitted assembly CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ForEmittedOutput)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.NotNull(p1.OutputFilePath); Assert.Equal("EmittedCSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); // if the assembly doesn't already exist, emit it now if (!File.Exists(p1.OutputFilePath)) { var c1 = await p1.GetCompilationAsync(); var result = c1.Emit(p1.OutputFilePath); Assert.True(result.Success); } } } protected async Task<Solution> SolutionAsync(params IBuilder[] inputs) { var files = GetSolutionFiles(inputs); CreateFiles(files); var solutionFileName = files.First(t => t.fileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase)).fileName; solutionFileName = GetSolutionFileName(solutionFileName); using (var workspace = CreateMSBuildWorkspace()) { return await workspace.OpenSolutionAsync(solutionFileName); } } protected static MSBuildWorkspace CreateMSBuildWorkspace(params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties)); } protected static MSBuildWorkspace CreateMSBuildWorkspace(HostServices hostServices, params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties), hostServices); } private static Dictionary<string, string> CreateProperties((string key, string value)[] additionalProperties) { var properties = new Dictionary<string, string>(); foreach (var (k, v) in additionalProperties) { properties.Add(k, v); } return properties; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEEventSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports System.Reflection Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' The class to represent all events imported from a PE/module. ''' </summary> Friend NotInheritable Class PEEventSymbol Inherits EventSymbol Private ReadOnly _name As String Private ReadOnly _flags As EventAttributes Private ReadOnly _containingType As PENamedTypeSymbol Private ReadOnly _handle As EventDefinitionHandle Private ReadOnly _eventType As TypeSymbol Private ReadOnly _addMethod As PEMethodSymbol Private ReadOnly _removeMethod As PEMethodSymbol Private ReadOnly _raiseMethod As PEMethodSymbol Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Private _lazyDocComment As Tuple(Of CultureInfo, String) Private _lazyCachedUseSiteInfo As CachedUseSiteInfo(Of AssemblySymbol) = CachedUseSiteInfo(Of AssemblySymbol).Uninitialized ' Indicates unknown state. Private _lazyObsoleteAttributeData As ObsoleteAttributeData = ObsoleteAttributeData.Uninitialized ' Distinct accessibility value to represent unset. Private Const s_unsetAccessibility As Integer = -1 Private _lazyDeclaredAccessibility As Integer = s_unsetAccessibility Friend Sub New(moduleSymbol As PEModuleSymbol, containingType As PENamedTypeSymbol, handle As EventDefinitionHandle, addMethod As PEMethodSymbol, removeMethod As PEMethodSymbol, raiseMethod As PEMethodSymbol) Debug.Assert(moduleSymbol IsNot Nothing) Debug.Assert(containingType IsNot Nothing) Debug.Assert(Not handle.IsNil) Debug.Assert(addMethod IsNot Nothing) Debug.Assert(removeMethod IsNot Nothing) Me._containingType = containingType Dim [module] = moduleSymbol.Module Dim eventType As EntityHandle Try [module].GetEventDefPropsOrThrow(handle, Me._name, Me._flags, eventType) Catch mrEx As BadImageFormatException If Me._name Is Nothing Then Me._name = String.Empty End If _lazyCachedUseSiteInfo.Initialize(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedEvent1, Me)) If eventType.IsNil Then Me._eventType = New UnsupportedMetadataTypeSymbol(mrEx) End If End Try Me._addMethod = addMethod Me._removeMethod = removeMethod Me._raiseMethod = raiseMethod Me._handle = handle If _eventType Is Nothing Then Dim metadataDecoder = New MetadataDecoder(moduleSymbol, containingType) Me._eventType = metadataDecoder.GetTypeOfToken(eventType) _eventType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(_eventType, handle, moduleSymbol) End If If Me._addMethod IsNot Nothing Then Me._addMethod.SetAssociatedEvent(Me, MethodKind.EventAdd) End If If Me._removeMethod IsNot Nothing Then Me._removeMethod.SetAssociatedEvent(Me, MethodKind.EventRemove) End If If Me._raiseMethod IsNot Nothing Then Me._raiseMethod.SetAssociatedEvent(Me, MethodKind.EventRaise) End If End Sub Public Overrides ReadOnly Property IsWindowsRuntimeEvent As Boolean Get Dim evt = DirectCast(Me.ContainingModule, PEModuleSymbol).GetEventRegistrationTokenType() ' WinRT events look different from normal events. ' The add method returns an EventRegistrationToken, ' and the remove method takes an EventRegistrationToken ' as a parameter. Return _ TypeSymbol.Equals(_addMethod.ReturnType, evt, TypeCompareKind.ConsiderEverything) AndAlso _addMethod.ParameterCount = 1 AndAlso _removeMethod.ParameterCount = 1 AndAlso TypeSymbol.Equals(_removeMethod.Parameters(0).Type, evt, TypeCompareKind.ConsiderEverything) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend ReadOnly Property EventFlags As EventAttributes Get Return _flags End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return (_flags And EventAttributes.SpecialName) <> 0 End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return (_flags And EventAttributes.RTSpecialName) <> 0 End Get End Property Friend ReadOnly Property Handle As EventDefinitionHandle Get Return _handle End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get If Me._lazyDeclaredAccessibility = s_unsetAccessibility Then Dim accessibility As Accessibility = PEPropertyOrEventHelpers.GetDeclaredAccessibilityFromAccessors(Me.AddMethod, Me.RemoveMethod) Interlocked.CompareExchange(Me._lazyDeclaredAccessibility, DirectCast(accessibility, Integer), s_unsetAccessibility) End If Return DirectCast(Me._lazyDeclaredAccessibility, Accessibility) End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsNotOverridable End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsOverrides End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Dim method = Me.AddMethod Return method Is Nothing OrElse method.IsShared End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return Me._eventType End Get End Property Public Overrides ReadOnly Property AddMethod As MethodSymbol Get Return Me._addMethod End Get End Property Public Overrides ReadOnly Property RemoveMethod As MethodSymbol Get Return Me._removeMethod End Get End Property Public Overrides ReadOnly Property RaiseMethod As MethodSymbol Get Return Me._raiseMethod End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _containingType.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(_lazyObsoleteAttributeData, _handle, DirectCast(ContainingModule, PEModuleSymbol)) Return _lazyObsoleteAttributeData End Get End Property Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) If _lazyCustomAttributes.IsDefault Then Dim containingPEModuleSymbol = DirectCast(ContainingModule(), PEModuleSymbol) containingPEModuleSymbol.LoadCustomAttributes(_handle, _lazyCustomAttributes) End If Return _lazyCustomAttributes End Function Friend Overrides Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Return GetAttributes() End Function Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of EventSymbol) Get If Me.AddMethod.ExplicitInterfaceImplementations.Length = 0 AndAlso Me.RemoveMethod.ExplicitInterfaceImplementations.Length = 0 Then Return ImmutableArray(Of EventSymbol).Empty End If Dim implementedEvents = PEPropertyOrEventHelpers.GetEventsForExplicitlyImplementedAccessor(Me.AddMethod) implementedEvents.IntersectWith(PEPropertyOrEventHelpers.GetEventsForExplicitlyImplementedAccessor(Me.RemoveMethod)) Dim builder = ArrayBuilder(Of EventSymbol).GetInstance() For Each [event] In implementedEvents builder.Add([event]) Next Return builder.ToImmutableAndFree() End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return PEDocumentationCommentUtils.GetDocumentationComment(Me, _containingType.ContainingPEModule, preferredCulture, cancellationToken, _lazyDocComment) End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim primaryDependency As AssemblySymbol = Me.PrimaryDependency If Not _lazyCachedUseSiteInfo.IsInitialized Then _lazyCachedUseSiteInfo.Initialize(primaryDependency, CalculateUseSiteInfo()) End If Return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency) End Function ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports System.Reflection Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' The class to represent all events imported from a PE/module. ''' </summary> Friend NotInheritable Class PEEventSymbol Inherits EventSymbol Private ReadOnly _name As String Private ReadOnly _flags As EventAttributes Private ReadOnly _containingType As PENamedTypeSymbol Private ReadOnly _handle As EventDefinitionHandle Private ReadOnly _eventType As TypeSymbol Private ReadOnly _addMethod As PEMethodSymbol Private ReadOnly _removeMethod As PEMethodSymbol Private ReadOnly _raiseMethod As PEMethodSymbol Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Private _lazyDocComment As Tuple(Of CultureInfo, String) Private _lazyCachedUseSiteInfo As CachedUseSiteInfo(Of AssemblySymbol) = CachedUseSiteInfo(Of AssemblySymbol).Uninitialized ' Indicates unknown state. Private _lazyObsoleteAttributeData As ObsoleteAttributeData = ObsoleteAttributeData.Uninitialized ' Distinct accessibility value to represent unset. Private Const s_unsetAccessibility As Integer = -1 Private _lazyDeclaredAccessibility As Integer = s_unsetAccessibility Friend Sub New(moduleSymbol As PEModuleSymbol, containingType As PENamedTypeSymbol, handle As EventDefinitionHandle, addMethod As PEMethodSymbol, removeMethod As PEMethodSymbol, raiseMethod As PEMethodSymbol) Debug.Assert(moduleSymbol IsNot Nothing) Debug.Assert(containingType IsNot Nothing) Debug.Assert(Not handle.IsNil) Debug.Assert(addMethod IsNot Nothing) Debug.Assert(removeMethod IsNot Nothing) Me._containingType = containingType Dim [module] = moduleSymbol.Module Dim eventType As EntityHandle Try [module].GetEventDefPropsOrThrow(handle, Me._name, Me._flags, eventType) Catch mrEx As BadImageFormatException If Me._name Is Nothing Then Me._name = String.Empty End If _lazyCachedUseSiteInfo.Initialize(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedEvent1, Me)) If eventType.IsNil Then Me._eventType = New UnsupportedMetadataTypeSymbol(mrEx) End If End Try Me._addMethod = addMethod Me._removeMethod = removeMethod Me._raiseMethod = raiseMethod Me._handle = handle If _eventType Is Nothing Then Dim metadataDecoder = New MetadataDecoder(moduleSymbol, containingType) Me._eventType = metadataDecoder.GetTypeOfToken(eventType) _eventType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(_eventType, handle, moduleSymbol) End If If Me._addMethod IsNot Nothing Then Me._addMethod.SetAssociatedEvent(Me, MethodKind.EventAdd) End If If Me._removeMethod IsNot Nothing Then Me._removeMethod.SetAssociatedEvent(Me, MethodKind.EventRemove) End If If Me._raiseMethod IsNot Nothing Then Me._raiseMethod.SetAssociatedEvent(Me, MethodKind.EventRaise) End If End Sub Public Overrides ReadOnly Property IsWindowsRuntimeEvent As Boolean Get Dim evt = DirectCast(Me.ContainingModule, PEModuleSymbol).GetEventRegistrationTokenType() ' WinRT events look different from normal events. ' The add method returns an EventRegistrationToken, ' and the remove method takes an EventRegistrationToken ' as a parameter. Return _ TypeSymbol.Equals(_addMethod.ReturnType, evt, TypeCompareKind.ConsiderEverything) AndAlso _addMethod.ParameterCount = 1 AndAlso _removeMethod.ParameterCount = 1 AndAlso TypeSymbol.Equals(_removeMethod.Parameters(0).Type, evt, TypeCompareKind.ConsiderEverything) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend ReadOnly Property EventFlags As EventAttributes Get Return _flags End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return (_flags And EventAttributes.SpecialName) <> 0 End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return (_flags And EventAttributes.RTSpecialName) <> 0 End Get End Property Friend ReadOnly Property Handle As EventDefinitionHandle Get Return _handle End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get If Me._lazyDeclaredAccessibility = s_unsetAccessibility Then Dim accessibility As Accessibility = PEPropertyOrEventHelpers.GetDeclaredAccessibilityFromAccessors(Me.AddMethod, Me.RemoveMethod) Interlocked.CompareExchange(Me._lazyDeclaredAccessibility, DirectCast(accessibility, Integer), s_unsetAccessibility) End If Return DirectCast(Me._lazyDeclaredAccessibility, Accessibility) End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsNotOverridable End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Dim method = Me.AddMethod Return (method IsNot Nothing) AndAlso method.IsOverrides End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Dim method = Me.AddMethod Return method Is Nothing OrElse method.IsShared End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return Me._eventType End Get End Property Public Overrides ReadOnly Property AddMethod As MethodSymbol Get Return Me._addMethod End Get End Property Public Overrides ReadOnly Property RemoveMethod As MethodSymbol Get Return Me._removeMethod End Get End Property Public Overrides ReadOnly Property RaiseMethod As MethodSymbol Get Return Me._raiseMethod End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _containingType.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(_lazyObsoleteAttributeData, _handle, DirectCast(ContainingModule, PEModuleSymbol)) Return _lazyObsoleteAttributeData End Get End Property Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) If _lazyCustomAttributes.IsDefault Then Dim containingPEModuleSymbol = DirectCast(ContainingModule(), PEModuleSymbol) containingPEModuleSymbol.LoadCustomAttributes(_handle, _lazyCustomAttributes) End If Return _lazyCustomAttributes End Function Friend Overrides Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Return GetAttributes() End Function Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of EventSymbol) Get If Me.AddMethod.ExplicitInterfaceImplementations.Length = 0 AndAlso Me.RemoveMethod.ExplicitInterfaceImplementations.Length = 0 Then Return ImmutableArray(Of EventSymbol).Empty End If Dim implementedEvents = PEPropertyOrEventHelpers.GetEventsForExplicitlyImplementedAccessor(Me.AddMethod) implementedEvents.IntersectWith(PEPropertyOrEventHelpers.GetEventsForExplicitlyImplementedAccessor(Me.RemoveMethod)) Dim builder = ArrayBuilder(Of EventSymbol).GetInstance() For Each [event] In implementedEvents builder.Add([event]) Next Return builder.ToImmutableAndFree() End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return PEDocumentationCommentUtils.GetDocumentationComment(Me, _containingType.ContainingPEModule, preferredCulture, cancellationToken, _lazyDocComment) End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim primaryDependency As AssemblySymbol = Me.PrimaryDependency If Not _lazyCachedUseSiteInfo.IsInitialized Then _lazyCachedUseSiteInfo.Initialize(primaryDependency, CalculateUseSiteInfo()) End If Return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency) End Function ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 ElseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [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_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 ElseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [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_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Server/VBCSCompilerTests/VBCSCompilerServerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CommandLine; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.IO; using System.IO.Pipes; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class VBCSCompilerServerTests : IDisposable { public TempRoot TempRoot { get; } = new TempRoot(); public void Dispose() { TempRoot.Dispose(); } public class StartupTests : VBCSCompilerServerTests { [Fact] [WorkItem(217709, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/217709")] public async Task ShadowCopyAnalyzerAssemblyLoaderMissingDirectory() { var baseDirectory = Path.Combine(Path.GetTempPath(), TestBase.GetUniqueName()); var loader = new ShadowCopyAnalyzerAssemblyLoader(baseDirectory); var task = loader.DeleteLeftoverDirectoriesTask; await task; Assert.False(task.IsFaulted); } } public class ShutdownTests : VBCSCompilerServerTests { internal XunitCompilerServerLogger Logger { get; } public ShutdownTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } private Task<int> RunShutdownAsync(string pipeName, bool waitForProcess = true, TimeSpan? timeout = null, CancellationToken cancellationToken = default(CancellationToken)) { var appSettings = new NameValueCollection(); return new BuildServerController(appSettings, Logger).RunShutdownAsync(pipeName, waitForProcess, timeout, cancellationToken); } [Fact] public async Task Standard() { using var serverData = await ServerUtil.CreateServer(Logger); var exitCode = await RunShutdownAsync(serverData.PipeName, waitForProcess: false); Assert.Equal(CommonCompiler.Succeeded, exitCode); // Await the server task here to verify it actually shuts down vs. us shutting down the server. var listener = await serverData.ServerTask; Assert.Equal( new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), listener.CompletionDataList.Single()); } /// <summary> /// If there is no server running with the specified pipe name then it's not running and hence /// shutdown succeeded. /// </summary> /// <returns></returns> [Fact] public async Task NoServerMutex() { var pipeName = Guid.NewGuid().ToString(); var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false); Assert.Equal(CommonCompiler.Succeeded, exitCode); } [Fact] [WorkItem(34880, "https://github.com/dotnet/roslyn/issues/34880")] public async Task NoServerConnection() { using (var readyMre = new ManualResetEvent(initialState: false)) using (var doneMre = new ManualResetEvent(initialState: false)) { var pipeName = Guid.NewGuid().ToString(); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); bool created = false; bool connected = false; var thread = new Thread(() => { using (var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created)) using (var stream = NamedPipeUtil.CreateServer(pipeName)) { readyMre.Set(); // Get a client connection and then immediately close it. Don't give any response. stream.WaitForConnection(); connected = true; stream.Close(); doneMre.WaitOne(); mutex.ReleaseMutex(); } }); // Block until the mutex and named pipe is setup. thread.Start(); readyMre.WaitOne(); var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false); // Let the fake server exit. doneMre.Set(); thread.Join(); Assert.Equal(CommonCompiler.Failed, exitCode); Assert.True(connected); Assert.True(created); } } /// <summary> /// Here the server doesn't respond to the shutdown request but successfully shuts down before /// the client can error out. /// </summary> /// <returns></returns> [Fact] [WorkItem(34880, "https://github.com/dotnet/roslyn/issues/34880")] public async Task ServerShutdownsDuringProcessing() { using (var readyMre = new ManualResetEvent(initialState: false)) using (var doneMre = new ManualResetEvent(initialState: false)) { var pipeName = Guid.NewGuid().ToString(); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); bool created = false; bool connected = false; var thread = new Thread(() => { using (var stream = NamedPipeUtil.CreateServer(pipeName)) { var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created); readyMre.Set(); stream.WaitForConnection(); connected = true; // Client is waiting for a response. Close the mutex now. Then close the connection // so the client gets an error. mutex.ReleaseMutex(); mutex.Dispose(); stream.Close(); doneMre.WaitOne(); } }); // Block until the mutex and named pipe is setup. thread.Start(); readyMre.WaitOne(); var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false); // Let the fake server exit. doneMre.Set(); thread.Join(); Assert.Equal(CommonCompiler.Succeeded, exitCode); Assert.True(connected); Assert.True(created); } } /// <summary> /// A shutdown request should not abort an existing compilation. It should be allowed to run to /// completion. /// </summary> [Fact] public async Task ShutdownDoesNotAbortCompilation() { using var startedMre = new ManualResetEvent(initialState: false); using var finishedMre = new ManualResetEvent(initialState: false); // Create a compilation that is guaranteed to complete after the shutdown is seen. var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { startedMre.Set(); finishedMre.WaitOne(); return ProtocolUtil.EmptyBuildResponse; }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); // Get the server to the point that it is running the compilation. var compileTask = serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest); startedMre.WaitOne(); // The compilation is now in progress, send the shutdown and verify that the // compilation is still running. await serverData.SendShutdownAsync(); Assert.False(compileTask.IsCompleted); // Now complete the compilation and verify that it actually ran to completion despite // there being a shutdown request. finishedMre.Set(); var response = await compileTask; Assert.True(response is CompletedBuildResponse { ReturnCode: 0 }); // Now verify the server actually shuts down since there is no work remaining. var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); } /// <summary> /// Multiple clients should be able to send shutdown requests to the server. /// </summary> [Fact] public async Task ShutdownRepeated() { using var startedMre = new ManualResetEvent(initialState: false); using var finishedMre = new ManualResetEvent(initialState: false); // Create a compilation that is guaranteed to complete after the shutdown is seen. var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { startedMre.Set(); finishedMre.WaitOne(); return ProtocolUtil.EmptyBuildResponse; }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); // Get the server to the point that it is running the compilation. var compileTask = serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest); startedMre.WaitOne(); // The compilation is now in progress, send the shutdown and verify that the // compilation is still running. await serverData.SendShutdownAsync(); await serverData.SendShutdownAsync(); // Now complete the compilation and verify that it actually ran to completion despite // there being a shutdown request. finishedMre.Set(); var response = await compileTask; Assert.True(response is CompletedBuildResponse { ReturnCode: 0 }); // Now verify the server actually shuts down since there is no work remaining. var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); } } public class KeepAliveTests : VBCSCompilerServerTests { internal XunitCompilerServerLogger Logger { get; } public KeepAliveTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } /// <summary> /// Ensure server hits keep alive when processing no connections /// </summary> [Fact] public async Task NoConnections() { var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => ProtocolUtil.EmptyBuildResponse); using var serverData = await ServerUtil.CreateServer( Logger, keepAlive: TimeSpan.FromSeconds(3), compilerServerHost: compilerServerHost); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.True(listener.KeepAliveHit); Assert.Equal(0, listener.CompletionDataList.Count); } /// <summary> /// Ensure server respects keep alive and shuts down after processing a single connection. /// </summary> [ConditionalTheory(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/46447")] [InlineData(1)] [InlineData(2)] [InlineData(3)] public async Task SimpleCases(int connectionCount) { var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => ProtocolUtil.EmptyBuildResponse); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var workingDirectory = TempRoot.CreateDirectory().Path; for (var i = 0; i < connectionCount; i++) { var request = i + 1 >= connectionCount ? ProtocolUtil.CreateEmptyCSharpWithKeepAlive(TimeSpan.FromSeconds(3), workingDirectory) : ProtocolUtil.EmptyCSharpBuildRequest; await serverData.SendAsync(request); } // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.True(listener.KeepAliveHit); Assert.Equal(connectionCount, listener.CompletionDataList.Count); Assert.All(listener.CompletionDataList, cd => Assert.Equal(CompletionReason.RequestCompleted, cd.Reason)); } /// <summary> /// Ensure server respects keep alive and shuts down after processing simultaneous connections. /// </summary> [ConditionalTheory(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/46447")] [InlineData(2)] [InlineData(3)] public async Task SimultaneousConnections(int connectionCount) { using var readyMre = new ManualResetEvent(initialState: false); var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { readyMre.WaitOne(); return ProtocolUtil.EmptyBuildResponse; }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var list = new List<Task>(); for (var i = 0; i < connectionCount; i++) { list.Add(serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest)); } readyMre.Set(); var workingDirectory = TempRoot.CreateDirectory().Path; await serverData.SendAsync(ProtocolUtil.CreateEmptyCSharpWithKeepAlive(TimeSpan.FromSeconds(3), workingDirectory)); await Task.WhenAll(list); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.True(listener.KeepAliveHit); Assert.Equal(connectionCount + 1, listener.CompletionDataList.Count); Assert.All(listener.CompletionDataList, cd => Assert.Equal(CompletionReason.RequestCompleted, cd.Reason)); } } public class MiscTests : VBCSCompilerServerTests { internal XunitCompilerServerLogger Logger { get; } public MiscTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } [Fact] public async Task CompilationExceptionShouldShutdown() { var hitCompilation = false; var compilerServerHost = new TestableCompilerServerHost(delegate { hitCompilation = true; throw new Exception(""); }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var response = await serverData.SendAsync(ProtocolUtil.EmptyBasicBuildRequest); Assert.True(response is RejectedBuildResponse); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single()); Assert.True(hitCompilation); } [Fact] public async Task AnalyzerInconsistencyShouldShutdown() { var compilerServerHost = new TestableCompilerServerHost(delegate { return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(Array.Empty<string>())); }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var response = await serverData.SendAsync(ProtocolUtil.EmptyBasicBuildRequest); Assert.True(response is AnalyzerInconsistencyBuildResponse); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single()); } } public class ParseCommandLineTests : VBCSCompilerServerTests { private string _pipeName; private bool _shutdown; private bool Parse(params string[] args) { return BuildServerController.ParseCommandLine(args, out _pipeName, out _shutdown); } [Fact] public void Nothing() { Assert.True(Parse()); Assert.Null(_pipeName); Assert.False(_shutdown); } [Fact] public void PipeOnly() { Assert.True(Parse("-pipename:test")); Assert.Equal("test", _pipeName); Assert.False(_shutdown); } [Fact] public void Shutdown() { Assert.True(Parse("-shutdown")); Assert.Null(_pipeName); Assert.True(_shutdown); } [Fact] public void PipeAndShutdown() { Assert.True(Parse("-pipename:test", "-shutdown")); Assert.Equal("test", _pipeName); Assert.True(_shutdown); } [Fact] public void BadArg() { Assert.False(Parse("-invalid")); Assert.False(Parse("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. #nullable disable using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.IO; using System.IO.Pipes; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class VBCSCompilerServerTests : IDisposable { public TempRoot TempRoot { get; } = new TempRoot(); public void Dispose() { TempRoot.Dispose(); } public class StartupTests : VBCSCompilerServerTests { [Fact] [WorkItem(217709, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/217709")] public async Task ShadowCopyAnalyzerAssemblyLoaderMissingDirectory() { var baseDirectory = Path.Combine(Path.GetTempPath(), TestBase.GetUniqueName()); var loader = new ShadowCopyAnalyzerAssemblyLoader(baseDirectory); var task = loader.DeleteLeftoverDirectoriesTask; await task; Assert.False(task.IsFaulted); } } public class ShutdownTests : VBCSCompilerServerTests { internal XunitCompilerServerLogger Logger { get; } public ShutdownTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } private Task<int> RunShutdownAsync(string pipeName, bool waitForProcess = true, TimeSpan? timeout = null, CancellationToken cancellationToken = default(CancellationToken)) { var appSettings = new NameValueCollection(); return new BuildServerController(appSettings, Logger).RunShutdownAsync(pipeName, waitForProcess, timeout, cancellationToken); } [Fact] public async Task Standard() { using var serverData = await ServerUtil.CreateServer(Logger); var exitCode = await RunShutdownAsync(serverData.PipeName, waitForProcess: false); Assert.Equal(CommonCompiler.Succeeded, exitCode); // Await the server task here to verify it actually shuts down vs. us shutting down the server. var listener = await serverData.ServerTask; Assert.Equal( new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), listener.CompletionDataList.Single()); } /// <summary> /// If there is no server running with the specified pipe name then it's not running and hence /// shutdown succeeded. /// </summary> /// <returns></returns> [Fact] public async Task NoServerMutex() { var pipeName = Guid.NewGuid().ToString(); var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false); Assert.Equal(CommonCompiler.Succeeded, exitCode); } [Fact] [WorkItem(34880, "https://github.com/dotnet/roslyn/issues/34880")] public async Task NoServerConnection() { using (var readyMre = new ManualResetEvent(initialState: false)) using (var doneMre = new ManualResetEvent(initialState: false)) { var pipeName = Guid.NewGuid().ToString(); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); bool created = false; bool connected = false; var thread = new Thread(() => { using (var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created)) using (var stream = NamedPipeUtil.CreateServer(pipeName)) { readyMre.Set(); // Get a client connection and then immediately close it. Don't give any response. stream.WaitForConnection(); connected = true; stream.Close(); doneMre.WaitOne(); mutex.ReleaseMutex(); } }); // Block until the mutex and named pipe is setup. thread.Start(); readyMre.WaitOne(); var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false); // Let the fake server exit. doneMre.Set(); thread.Join(); Assert.Equal(CommonCompiler.Failed, exitCode); Assert.True(connected); Assert.True(created); } } /// <summary> /// Here the server doesn't respond to the shutdown request but successfully shuts down before /// the client can error out. /// </summary> /// <returns></returns> [Fact] [WorkItem(34880, "https://github.com/dotnet/roslyn/issues/34880")] public async Task ServerShutdownsDuringProcessing() { using (var readyMre = new ManualResetEvent(initialState: false)) using (var doneMre = new ManualResetEvent(initialState: false)) { var pipeName = Guid.NewGuid().ToString(); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); bool created = false; bool connected = false; var thread = new Thread(() => { using (var stream = NamedPipeUtil.CreateServer(pipeName)) { var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created); readyMre.Set(); stream.WaitForConnection(); connected = true; // Client is waiting for a response. Close the mutex now. Then close the connection // so the client gets an error. mutex.ReleaseMutex(); mutex.Dispose(); stream.Close(); doneMre.WaitOne(); } }); // Block until the mutex and named pipe is setup. thread.Start(); readyMre.WaitOne(); var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false); // Let the fake server exit. doneMre.Set(); thread.Join(); Assert.Equal(CommonCompiler.Succeeded, exitCode); Assert.True(connected); Assert.True(created); } } /// <summary> /// A shutdown request should not abort an existing compilation. It should be allowed to run to /// completion. /// </summary> [Fact] public async Task ShutdownDoesNotAbortCompilation() { using var startedMre = new ManualResetEvent(initialState: false); using var finishedMre = new ManualResetEvent(initialState: false); // Create a compilation that is guaranteed to complete after the shutdown is seen. var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { startedMre.Set(); finishedMre.WaitOne(); return ProtocolUtil.EmptyBuildResponse; }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); // Get the server to the point that it is running the compilation. var compileTask = serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest); startedMre.WaitOne(); // The compilation is now in progress, send the shutdown and verify that the // compilation is still running. await serverData.SendShutdownAsync(); Assert.False(compileTask.IsCompleted); // Now complete the compilation and verify that it actually ran to completion despite // there being a shutdown request. finishedMre.Set(); var response = await compileTask; Assert.True(response is CompletedBuildResponse { ReturnCode: 0 }); // Now verify the server actually shuts down since there is no work remaining. var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); } /// <summary> /// Multiple clients should be able to send shutdown requests to the server. /// </summary> [Fact] public async Task ShutdownRepeated() { using var startedMre = new ManualResetEvent(initialState: false); using var finishedMre = new ManualResetEvent(initialState: false); // Create a compilation that is guaranteed to complete after the shutdown is seen. var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { startedMre.Set(); finishedMre.WaitOne(); return ProtocolUtil.EmptyBuildResponse; }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); // Get the server to the point that it is running the compilation. var compileTask = serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest); startedMre.WaitOne(); // The compilation is now in progress, send the shutdown and verify that the // compilation is still running. await serverData.SendShutdownAsync(); await serverData.SendShutdownAsync(); // Now complete the compilation and verify that it actually ran to completion despite // there being a shutdown request. finishedMre.Set(); var response = await compileTask; Assert.True(response is CompletedBuildResponse { ReturnCode: 0 }); // Now verify the server actually shuts down since there is no work remaining. var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); } } public class KeepAliveTests : VBCSCompilerServerTests { internal XunitCompilerServerLogger Logger { get; } public KeepAliveTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } /// <summary> /// Ensure server hits keep alive when processing no connections /// </summary> [Fact] public async Task NoConnections() { var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => ProtocolUtil.EmptyBuildResponse); using var serverData = await ServerUtil.CreateServer( Logger, keepAlive: TimeSpan.FromSeconds(3), compilerServerHost: compilerServerHost); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.True(listener.KeepAliveHit); Assert.Equal(0, listener.CompletionDataList.Count); } /// <summary> /// Ensure server respects keep alive and shuts down after processing a single connection. /// </summary> [ConditionalTheory(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/46447")] [InlineData(1)] [InlineData(2)] [InlineData(3)] public async Task SimpleCases(int connectionCount) { var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => ProtocolUtil.EmptyBuildResponse); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var workingDirectory = TempRoot.CreateDirectory().Path; for (var i = 0; i < connectionCount; i++) { var request = i + 1 >= connectionCount ? ProtocolUtil.CreateEmptyCSharpWithKeepAlive(TimeSpan.FromSeconds(3), workingDirectory) : ProtocolUtil.EmptyCSharpBuildRequest; await serverData.SendAsync(request); } // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.True(listener.KeepAliveHit); Assert.Equal(connectionCount, listener.CompletionDataList.Count); Assert.All(listener.CompletionDataList, cd => Assert.Equal(CompletionReason.RequestCompleted, cd.Reason)); } /// <summary> /// Ensure server respects keep alive and shuts down after processing simultaneous connections. /// </summary> [ConditionalTheory(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/46447")] [InlineData(2)] [InlineData(3)] public async Task SimultaneousConnections(int connectionCount) { using var readyMre = new ManualResetEvent(initialState: false); var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { readyMre.WaitOne(); return ProtocolUtil.EmptyBuildResponse; }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var list = new List<Task>(); for (var i = 0; i < connectionCount; i++) { list.Add(serverData.SendAsync(ProtocolUtil.EmptyCSharpBuildRequest)); } readyMre.Set(); var workingDirectory = TempRoot.CreateDirectory().Path; await serverData.SendAsync(ProtocolUtil.CreateEmptyCSharpWithKeepAlive(TimeSpan.FromSeconds(3), workingDirectory)); await Task.WhenAll(list); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.True(listener.KeepAliveHit); Assert.Equal(connectionCount + 1, listener.CompletionDataList.Count); Assert.All(listener.CompletionDataList, cd => Assert.Equal(CompletionReason.RequestCompleted, cd.Reason)); } } public class MiscTests : VBCSCompilerServerTests { internal XunitCompilerServerLogger Logger { get; } public MiscTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } [Fact] public async Task CompilationExceptionShouldShutdown() { var hitCompilation = false; var compilerServerHost = new TestableCompilerServerHost(delegate { hitCompilation = true; throw new Exception(""); }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var response = await serverData.SendAsync(ProtocolUtil.EmptyBasicBuildRequest); Assert.True(response is RejectedBuildResponse); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single()); Assert.True(hitCompilation); } [Fact] public async Task AnalyzerInconsistencyShouldShutdown() { var compilerServerHost = new TestableCompilerServerHost(delegate { return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(Array.Empty<string>())); }); using var serverData = await ServerUtil.CreateServer(Logger, compilerServerHost: compilerServerHost); var response = await serverData.SendAsync(ProtocolUtil.EmptyBasicBuildRequest); Assert.True(response is AnalyzerInconsistencyBuildResponse); // Don't use Complete here because we want to see the server shutdown naturally var listener = await serverData.ServerTask; Assert.False(listener.KeepAliveHit); Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single()); } } public class ParseCommandLineTests : VBCSCompilerServerTests { private string _pipeName; private bool _shutdown; private bool Parse(params string[] args) { return BuildServerController.ParseCommandLine(args, out _pipeName, out _shutdown); } [Fact] public void Nothing() { Assert.True(Parse()); Assert.Null(_pipeName); Assert.False(_shutdown); } [Fact] public void PipeOnly() { Assert.True(Parse("-pipename:test")); Assert.Equal("test", _pipeName); Assert.False(_shutdown); } [Fact] public void Shutdown() { Assert.True(Parse("-shutdown")); Assert.Null(_pipeName); Assert.True(_shutdown); } [Fact] public void PipeAndShutdown() { Assert.True(Parse("-pipename:test", "-shutdown")); Assert.Equal("test", _pipeName); Assert.True(_shutdown); } [Fact] public void BadArg() { Assert.False(Parse("-invalid")); Assert.False(Parse("name")); } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/VisualBasic/Portable/Workspace/LanguageServices/VisualBasicSyntaxTreeFactoryService.PositionalSyntaxReference.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class VisualBasicSyntaxTreeFactoryServiceFactory Partial Friend Class VisualBasicSyntaxTreeFactoryService ''' <summary> ''' Represents a syntax reference that doesn't actually hold onto the referenced node. ''' Instead, enough data is held onto so that the node can be recovered and returned if ''' necessary. ''' </summary> Private Class PositionalSyntaxReference Inherits SyntaxReference Private ReadOnly _tree As SyntaxTree Private ReadOnly _span As TextSpan Private ReadOnly _kind As SyntaxKind Public Sub New(tree As SyntaxTree, node As SyntaxNode) _tree = tree _span = node.Span _kind = node.Kind() End Sub Public Overrides ReadOnly Property SyntaxTree As SyntaxTree Get Return _tree End Get End Property Public Overrides ReadOnly Property Span As TextSpan Get Return _span End Get End Property Public Overrides Function GetSyntax(Optional cancellationToken As CancellationToken = Nothing) As SyntaxNode Return DirectCast(Me.GetNode(_tree.GetRoot(cancellationToken)), VisualBasicSyntaxNode) End Function Public Overrides Async Function GetSyntaxAsync(Optional cancellationToken As CancellationToken = Nothing) As Task(Of SyntaxNode) Dim root = Await _tree.GetRootAsync(cancellationToken).ConfigureAwait(False) Return Me.GetNode(root) End Function Private Function GetNode(root As SyntaxNode) As SyntaxNode ' Find our node going down in the tree. ' Try not going deeper than needed. Dim current = root Dim spanStart As Integer = Me._span.Start While current.FullSpan.Contains(spanStart) If current.Kind = Me._kind AndAlso current.Span = Me._span Then Return current End If Dim nodeOrToken = current.ChildThatContainsPosition(spanStart) ' we have got a token. It means that the node is in structured trivia If nodeOrToken.IsToken Then Return GetNodeInStructuredTrivia(current) End If current = nodeOrToken.AsNode End While Throw New InvalidOperationException("reference to a node that does not exist?") End Function Private Function GetNodeInStructuredTrivia(parent As SyntaxNode) As SyntaxNode ' Syntax references to nonterminals in structured trivia should be uncommon. ' Provide more efficient implementation if that is not true Return parent.DescendantNodes(Me._span, descendIntoTrivia:=True). First(Function(node) Return node.Kind = Me._kind AndAlso node.Span = Me._span End Function) End Function End Class End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class VisualBasicSyntaxTreeFactoryServiceFactory Partial Friend Class VisualBasicSyntaxTreeFactoryService ''' <summary> ''' Represents a syntax reference that doesn't actually hold onto the referenced node. ''' Instead, enough data is held onto so that the node can be recovered and returned if ''' necessary. ''' </summary> Private Class PositionalSyntaxReference Inherits SyntaxReference Private ReadOnly _tree As SyntaxTree Private ReadOnly _span As TextSpan Private ReadOnly _kind As SyntaxKind Public Sub New(tree As SyntaxTree, node As SyntaxNode) _tree = tree _span = node.Span _kind = node.Kind() End Sub Public Overrides ReadOnly Property SyntaxTree As SyntaxTree Get Return _tree End Get End Property Public Overrides ReadOnly Property Span As TextSpan Get Return _span End Get End Property Public Overrides Function GetSyntax(Optional cancellationToken As CancellationToken = Nothing) As SyntaxNode Return DirectCast(Me.GetNode(_tree.GetRoot(cancellationToken)), VisualBasicSyntaxNode) End Function Public Overrides Async Function GetSyntaxAsync(Optional cancellationToken As CancellationToken = Nothing) As Task(Of SyntaxNode) Dim root = Await _tree.GetRootAsync(cancellationToken).ConfigureAwait(False) Return Me.GetNode(root) End Function Private Function GetNode(root As SyntaxNode) As SyntaxNode ' Find our node going down in the tree. ' Try not going deeper than needed. Dim current = root Dim spanStart As Integer = Me._span.Start While current.FullSpan.Contains(spanStart) If current.Kind = Me._kind AndAlso current.Span = Me._span Then Return current End If Dim nodeOrToken = current.ChildThatContainsPosition(spanStart) ' we have got a token. It means that the node is in structured trivia If nodeOrToken.IsToken Then Return GetNodeInStructuredTrivia(current) End If current = nodeOrToken.AsNode End While Throw New InvalidOperationException("reference to a node that does not exist?") End Function Private Function GetNodeInStructuredTrivia(parent As SyntaxNode) As SyntaxNode ' Syntax references to nonterminals in structured trivia should be uncommon. ' Provide more efficient implementation if that is not true Return parent.DescendantNodes(Me._span, descendIntoTrivia:=True). First(Function(node) Return node.Kind = Me._kind AndAlso node.Span = Me._span End Function) End Function End Class End Class End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/ChangeSignature/ReorderParameters.InvocationLocations.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests #Region "Methods" <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeBeforeMethodName() As Task Dim markup = <Text><![CDATA[ Class C Public Sub $$Goo(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeInParameterList() As Task Dim markup = <Text><![CDATA[ Class C Public Sub Goo(x As Integer, $$y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeAfterParameterList() As Task Dim markup = <Text><![CDATA[ Class C Public Sub Goo(x As Integer, y As String)$$ End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeBeforeMethodDeclaration() As Task Dim markup = <Text><![CDATA[ Class C $$Public Sub Goo(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = DirectCast(Nothing, System.IFormattable).To$$String("test", Nothing) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = $$DirectCast(Nothing, System.IFormattable).ToString("test", Nothing) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = DirectCast(Nothing, System.IFormattable).ToString("test", $$Nothing) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = DirectCast(Nothing, System.IFormattable).ToString("test", Nothing)$$ End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeInMethodBody() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) $$ End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) $$T(x, y) End Sub Public Sub T(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) T(y, x) End Sub Public Sub T(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_ArgumentList() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) T(x, $$y) End Sub Public Sub T(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) T(y, x) End Sub Public Sub T(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_NestedCalls1() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D($$J(x, y), y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(J(y, x), y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(y As String, x As Integer) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_NestedCalls2() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D$$(J(x, y), y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(y, J(x, y)) End Sub Public Sub D(y As String, x As Integer) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_NestedCalls3() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(J(x, y), $$y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(y, J(x, y)) End Sub Public Sub D(y As String, x As Integer) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_OnlyCandidateSymbols() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) End Sub Public Sub M(x As Integer, y As Double) End Sub Public Sub Test() $$M("Test", 5) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(y As String, x As Integer) End Sub Public Sub M(x As Integer, y As Double) End Sub Public Sub Test() M(5, "Test") End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeInConstructor() As Task Dim markup = <Text><![CDATA[ Class C Public Sub New(x As Integer, y As String) Dim a = 5$$ Dim b = 6 End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub New(y As String, x As Integer) Dim a = 5 Dim b = 6 End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function #End Region #Region "Properties" <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeAtBeginningOfDeclaration() As Task Dim markup = <Text><![CDATA[ Class C $$Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InParameters() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, $$ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeAtEndOfDeclaration() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer$$ Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeInAccessor() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5$$ End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeOnReference_BeforeTarget() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = $$c(1, 2) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = c(2, 1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeOnReference_InArgumentList() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = c(1, 2$$) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = c(2, 1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function #End Region #Region "Delegates" <Fact(Skip:="860578"), Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderDelegateParameters_ObjectCreation1() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub Del(x As Integer, y As Integer) Sub T() Dim x = New $$Del(Sub(a, b) End Sub) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Delegate Sub Del(y As Integer, x As Integer) Sub T() Dim x = New Del(Sub(b, a) End Sub) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact(Skip:="860578"), Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderDelegateParameters_ObjectCreation2() As Task Dim markup = <Text><![CDATA[ Class C(Of T) Delegate Sub Del(x As T, y As T) End Class Class Test Sub M() Dim x = New C(Of Integer).$$Del(Sub(a, b) End Sub) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C(Of T) Delegate Sub Del(y As T, x As T) End Class Class Test Sub M() Dim x = New C(Of Integer).Del(Sub(b, a) End Sub) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function #End Region #Region "Code Refactoring" <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_InMethodDeclaration() As Threading.Tasks.Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer[||], y As Integer) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Sub Goo(y As Integer, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction:=True, updatedSignature:=permutation, expectedCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_NotInMethodBody() As Threading.Tasks.Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer, y As Integer) [||] End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_InCallSite_ViaCommand() As Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer, y As Integer) Goo($$1, 2) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Sub Goo(y As Integer, x As Integer) Goo(2, 1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_InCallSite_ViaCodeAction() As Threading.Tasks.Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer, y As Integer) Goo([||]1, 2) End Sub End Class]]></Text>.NormalizedValue() Await TestMissingAsync(markup) End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests #Region "Methods" <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeBeforeMethodName() As Task Dim markup = <Text><![CDATA[ Class C Public Sub $$Goo(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeInParameterList() As Task Dim markup = <Text><![CDATA[ Class C Public Sub Goo(x As Integer, $$y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeAfterParameterList() As Task Dim markup = <Text><![CDATA[ Class C Public Sub Goo(x As Integer, y As String)$$ End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeBeforeMethodDeclaration() As Task Dim markup = <Text><![CDATA[ Class C $$Public Sub Goo(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub Goo(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = DirectCast(Nothing, System.IFormattable).To$$String("test", Nothing) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = $$DirectCast(Nothing, System.IFormattable).ToString("test", Nothing) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = DirectCast(Nothing, System.IFormattable).ToString("test", $$Nothing) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) Dim m = DirectCast(Nothing, System.IFormattable).ToString("test", Nothing)$$ End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, expectedSuccess:=False, expectedFailureReason:=ChangeSignatureFailureKind.DefinedInMetadata) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeInMethodBody() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) $$ End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) $$T(x, y) End Sub Public Sub T(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) T(y, x) End Sub Public Sub T(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_ArgumentList() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) T(x, $$y) End Sub Public Sub T(x As Integer, y As String) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) T(y, x) End Sub Public Sub T(y As String, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_NestedCalls1() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D($$J(x, y), y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(J(y, x), y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(y As String, x As Integer) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_NestedCalls2() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D$$(J(x, y), y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(y, J(x, y)) End Sub Public Sub D(y As String, x As Integer) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_NestedCalls3() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(J(x, y), $$y) End Sub Public Sub D(x As Integer, y As String) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) D(y, J(x, y)) End Sub Public Sub D(y As String, x As Integer) End Sub Public Function J(x As Integer, y As String) As Integer Return 1 End Function End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeOnReference_OnlyCandidateSymbols() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(x As Integer, y As String) End Sub Public Sub M(x As Integer, y As Double) End Sub Public Sub Test() $$M("Test", 5) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub M(y As String, x As Integer) End Sub Public Sub M(x As Integer, y As Double) End Sub Public Sub Test() M(5, "Test") End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderMethodParameters_InvokeInConstructor() As Task Dim markup = <Text><![CDATA[ Class C Public Sub New(x As Integer, y As String) Dim a = 5$$ Dim b = 6 End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Public Sub New(y As String, x As Integer) Dim a = 5 Dim b = 6 End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function #End Region #Region "Properties" <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeAtBeginningOfDeclaration() As Task Dim markup = <Text><![CDATA[ Class C $$Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InParameters() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, $$ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeAtEndOfDeclaration() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer$$ Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeInAccessor() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5$$ End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeOnReference_BeforeTarget() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = $$c(1, 2) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = c(2, 1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderIndexerParameters_InvokeOnReference_InArgumentList() As Task Dim markup = <Text><![CDATA[ Class C Default Public Property Item(ByVal index1 As Integer, ByVal index2 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = c(1, 2$$) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Default Public Property Item(ByVal index2 As Integer, ByVal index1 As Integer) As Integer Get Return 5 End Get Set(value As Integer) End Set End Property Sub Goo() Dim c = New C() Dim x = c(2, 1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function #End Region #Region "Delegates" <Fact(Skip:="860578"), Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderDelegateParameters_ObjectCreation1() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub Del(x As Integer, y As Integer) Sub T() Dim x = New $$Del(Sub(a, b) End Sub) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Delegate Sub Del(y As Integer, x As Integer) Sub T() Dim x = New Del(Sub(b, a) End Sub) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact(Skip:="860578"), Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestReorderDelegateParameters_ObjectCreation2() As Task Dim markup = <Text><![CDATA[ Class C(Of T) Delegate Sub Del(x As T, y As T) End Class Class Test Sub M() Dim x = New C(Of Integer).$$Del(Sub(a, b) End Sub) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C(Of T) Delegate Sub Del(y As T, x As T) End Class Class Test Sub M() Dim x = New C(Of Integer).Del(Sub(b, a) End Sub) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function #End Region #Region "Code Refactoring" <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_InMethodDeclaration() As Threading.Tasks.Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer[||], y As Integer) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Sub Goo(y As Integer, x As Integer) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction:=True, updatedSignature:=permutation, expectedCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_NotInMethodBody() As Threading.Tasks.Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer, y As Integer) [||] End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_InCallSite_ViaCommand() As Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer, y As Integer) Goo($$1, 2) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = {1, 0} Dim updatedCode = <Text><![CDATA[ Class C Sub Goo(y As Integer, x As Integer) Goo(2, 1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function ReorderIndexerParameters_CodeRefactoring_InCallSite_ViaCodeAction() As Threading.Tasks.Task Dim markup = <Text><![CDATA[ Class C Sub Goo(x As Integer, y As Integer) Goo([||]1, 2) End Sub End Class]]></Text>.NormalizedValue() Await TestMissingAsync(markup) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/xlf/VSPackage.fr.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="fr" original="../VSPackage.resx"> <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="fr" original="../VSPackage.resx"> <body /> </file> </xliff>
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declStatement)) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declarationStatement) || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (!(pattern.Designation is SingleVariableDesignationSyntax designation)) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); foreach (var argument in AnalyzerResult.MethodParameters) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax || syntaxNode is LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declStatement)) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declarationStatement) || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (!(pattern.Designation is SingleVariableDesignationSyntax designation)) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); foreach (var argument in AnalyzerResult.MethodParameters) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax || syntaxNode is LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Metadata/DynamicAnalysisDataReader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable // TODO (https://github.com/dotnet/testimpact/issues/84): delete this using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal struct DynamicAnalysisDocument { public readonly BlobHandle Name; public readonly GuidHandle HashAlgorithm; public readonly BlobHandle Hash; public DynamicAnalysisDocument(BlobHandle name, GuidHandle hashAlgorithm, BlobHandle hash) { Name = name; HashAlgorithm = hashAlgorithm; Hash = hash; } } internal struct DynamicAnalysisMethod { public readonly BlobHandle Blob; public DynamicAnalysisMethod(BlobHandle blob) { Blob = blob; } } internal struct DynamicAnalysisSpan { public readonly int DocumentRowId; public readonly int StartLine; public readonly int StartColumn; public readonly int EndLine; public readonly int EndColumn; public DynamicAnalysisSpan(int documentRowId, int startLine, int startColumn, int endLine, int endColumn) { DocumentRowId = documentRowId; StartLine = startLine; StartColumn = startColumn; EndLine = endLine; EndColumn = endColumn; } } internal sealed unsafe class DynamicAnalysisDataReader { public ImmutableArray<DynamicAnalysisDocument> Documents { get; } public ImmutableArray<DynamicAnalysisMethod> Methods { get; } private readonly Blob _guidHeapBlob; private readonly Blob _blobHeapBlob; private const int GuidSize = 16; public DynamicAnalysisDataReader(byte* buffer, int size) { var reader = new BlobReader(buffer, size); // header: if (reader.ReadByte() != 'D' || reader.ReadByte() != 'A' || reader.ReadByte() != 'M' || reader.ReadByte() != 'D') { throw new BadImageFormatException(); } // version byte major = reader.ReadByte(); byte minor = reader.ReadByte(); if (major != 0 || minor < 1 || minor > 2) { throw new NotSupportedException(); } // table sizes: int documentRowCount = reader.ReadInt32(); int methodSpanRowCount = reader.ReadInt32(); // blob heap sizes: int stringHeapSize = (minor == 1) ? reader.ReadInt32() : 0; int userStringHeapSize = (minor == 1) ? reader.ReadInt32() : 0; int guidHeapSize = reader.ReadInt32(); int blobHeapSize = reader.ReadInt32(); // TODO: check size ranges bool isBlobHeapSmall = blobHeapSize <= ushort.MaxValue; bool isGuidHeapSmall = guidHeapSize / GuidSize <= ushort.MaxValue; var documentsBuilder = ArrayBuilder<DynamicAnalysisDocument>.GetInstance(documentRowCount); for (int i = 0; i < documentRowCount; i++) { var name = MetadataTokens.BlobHandle(ReadReference(ref reader, isBlobHeapSmall)); var hashAlgorithm = MetadataTokens.GuidHandle(ReadReference(ref reader, isGuidHeapSmall)); var hash = MetadataTokens.BlobHandle(ReadReference(ref reader, isBlobHeapSmall)); documentsBuilder.Add(new DynamicAnalysisDocument(name, hashAlgorithm, hash)); } Documents = documentsBuilder.ToImmutableAndFree(); var methodsBuilder = ArrayBuilder<DynamicAnalysisMethod>.GetInstance(methodSpanRowCount); for (int i = 0; i < methodSpanRowCount; i++) { methodsBuilder.Add(new DynamicAnalysisMethod(MetadataTokens.BlobHandle(ReadReference(ref reader, isBlobHeapSmall)))); } Methods = methodsBuilder.ToImmutableAndFree(); int stringHeapOffset = reader.Offset; int userStringHeapOffset = stringHeapOffset + stringHeapSize; int guidHeapOffset = userStringHeapOffset + userStringHeapSize; int blobHeapOffset = guidHeapOffset + guidHeapSize; if (reader.Length != blobHeapOffset + blobHeapSize) { throw new BadImageFormatException(); } _guidHeapBlob = new Blob(buffer + guidHeapOffset, guidHeapSize); _blobHeapBlob = new Blob(buffer + blobHeapOffset, blobHeapSize); } public static DynamicAnalysisDataReader TryCreateFromPE(PEReader peReader, string resourceName) { // TODO: review all range checks, better error messages var mdReader = peReader.GetMetadataReader(); long offset = -1; foreach (var resourceHandle in mdReader.ManifestResources) { var resource = mdReader.GetManifestResource(resourceHandle); if (resource.Implementation.IsNil && resource.Attributes == ManifestResourceAttributes.Private && mdReader.StringComparer.Equals(resource.Name, resourceName)) { offset = resource.Offset; } } if (offset < 0) { return null; } var resourcesDir = peReader.PEHeaders.CorHeader.ResourcesDirectory; if (resourcesDir.Size < 0) { throw new BadImageFormatException(); } if (!peReader.PEHeaders.TryGetDirectoryOffset(resourcesDir, out var start)) { return null; } var peImage = peReader.GetEntireImage(); if (start >= peImage.Length - resourcesDir.Size) { throw new BadImageFormatException(); } byte* resourceStart = peImage.Pointer + start; int resourceSize = *(int*)resourceStart; if (resourceSize > resourcesDir.Size - sizeof(int)) { throw new BadImageFormatException(); } return new DynamicAnalysisDataReader(resourceStart + sizeof(int), resourceSize); } private static int ReadReference(ref BlobReader reader, bool smallRefSize) { return smallRefSize ? reader.ReadUInt16() : reader.ReadInt32(); } public ImmutableArray<DynamicAnalysisSpan> GetSpans(BlobHandle handle) { if (handle.IsNil) { return ImmutableArray<DynamicAnalysisSpan>.Empty; } var builder = ArrayBuilder<DynamicAnalysisSpan>.GetInstance(); var reader = GetBlobReader(handle); // header: int documentRowId = ReadDocumentRowId(ref reader); int previousStartLine = -1; ushort previousStartColumn = 0; // records: while (reader.RemainingBytes > 0) { ReadDeltaLinesAndColumns(ref reader, out var deltaLines, out var deltaColumns); // document: if (deltaLines == 0 && deltaColumns == 0) { documentRowId = ReadDocumentRowId(ref reader); continue; } int startLine; ushort startColumn; // delta Start Line & Column: if (previousStartLine < 0) { Debug.Assert(previousStartColumn == 0); startLine = ReadLine(ref reader); startColumn = ReadColumn(ref reader); } else { startLine = AddLines(previousStartLine, reader.ReadCompressedSignedInteger()); startColumn = AddColumns(previousStartColumn, reader.ReadCompressedSignedInteger()); } previousStartLine = startLine; previousStartColumn = startColumn; int endLine = AddLines(startLine, deltaLines); int endColumn = AddColumns(startColumn, deltaColumns); var linePositionSpan = new DynamicAnalysisSpan(documentRowId, startLine, startColumn, endLine, endColumn); builder.Add(linePositionSpan); } return builder.ToImmutableAndFree(); } //TODO: some of the helpers below should be provided by System.Reflection.Metadata private unsafe struct Blob { public readonly byte* Pointer; public readonly int Length; public Blob(byte* pointer, int length) { Pointer = pointer; Length = length; } } public Guid GetGuid(GuidHandle handle) { if (handle.IsNil) { return default(Guid); } int offset = (MetadataTokens.GetHeapOffset(handle) - 1) * GuidSize; if (offset + GuidSize > _guidHeapBlob.Length) { throw new BadImageFormatException(); } return *(Guid*)(_guidHeapBlob.Pointer + offset); } internal byte[] GetBytes(BlobHandle handle) { var reader = GetBlobReader(handle); return reader.ReadBytes(reader.Length); } private BlobReader GetBlobReader(BlobHandle handle) { int offset = MetadataTokens.GetHeapOffset(handle); byte* start = _blobHeapBlob.Pointer + offset; var reader = new BlobReader(start, _blobHeapBlob.Length - offset); int size = reader.ReadCompressedInteger(); return new BlobReader(start + reader.Offset, size); } public string GetDocumentName(BlobHandle handle) { var blobReader = GetBlobReader(handle); // Spec: separator is an ASCII encoded character in range [0x01, 0x7F], or byte 0 to represent an empty separator. int separator = blobReader.ReadByte(); if (separator > 0x7f) { throw new BadImageFormatException(string.Format("Invalid document name", separator)); } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; bool isFirstPart = true; while (blobReader.RemainingBytes > 0) { if (separator != 0 && !isFirstPart) { builder.Append((char)separator); } var partReader = GetBlobReader(blobReader.ReadBlobHandle()); // TODO: avoid allocating temp string (https://github.com/dotnet/corefx/issues/2102) builder.Append(partReader.ReadUTF8(partReader.Length)); isFirstPart = false; } return pooledBuilder.ToStringAndFree(); } private void ReadDeltaLinesAndColumns(ref BlobReader reader, out int deltaLines, out int deltaColumns) { deltaLines = reader.ReadCompressedInteger(); deltaColumns = (deltaLines == 0) ? reader.ReadCompressedInteger() : reader.ReadCompressedSignedInteger(); } private int ReadLine(ref BlobReader reader) { return reader.ReadCompressedInteger(); } private ushort ReadColumn(ref BlobReader reader) { int column = reader.ReadCompressedInteger(); if (column > ushort.MaxValue) { throw new BadImageFormatException("SequencePointValueOutOfRange"); } return (ushort)column; } private int AddLines(int value, int delta) { int result = unchecked(value + delta); if (result < 0) { throw new BadImageFormatException("SequencePointValueOutOfRange"); } return result; } private ushort AddColumns(ushort value, int delta) { int result = unchecked(value + delta); if (result < 0 || result >= ushort.MaxValue) { throw new BadImageFormatException("SequencePointValueOutOfRange"); } return (ushort)result; } private int ReadDocumentRowId(ref BlobReader reader) { int rowId = reader.ReadCompressedInteger(); if (rowId == 0) { throw new BadImageFormatException("Invalid handle"); } return rowId; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable // TODO (https://github.com/dotnet/testimpact/issues/84): delete this using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal struct DynamicAnalysisDocument { public readonly BlobHandle Name; public readonly GuidHandle HashAlgorithm; public readonly BlobHandle Hash; public DynamicAnalysisDocument(BlobHandle name, GuidHandle hashAlgorithm, BlobHandle hash) { Name = name; HashAlgorithm = hashAlgorithm; Hash = hash; } } internal struct DynamicAnalysisMethod { public readonly BlobHandle Blob; public DynamicAnalysisMethod(BlobHandle blob) { Blob = blob; } } internal struct DynamicAnalysisSpan { public readonly int DocumentRowId; public readonly int StartLine; public readonly int StartColumn; public readonly int EndLine; public readonly int EndColumn; public DynamicAnalysisSpan(int documentRowId, int startLine, int startColumn, int endLine, int endColumn) { DocumentRowId = documentRowId; StartLine = startLine; StartColumn = startColumn; EndLine = endLine; EndColumn = endColumn; } } internal sealed unsafe class DynamicAnalysisDataReader { public ImmutableArray<DynamicAnalysisDocument> Documents { get; } public ImmutableArray<DynamicAnalysisMethod> Methods { get; } private readonly Blob _guidHeapBlob; private readonly Blob _blobHeapBlob; private const int GuidSize = 16; public DynamicAnalysisDataReader(byte* buffer, int size) { var reader = new BlobReader(buffer, size); // header: if (reader.ReadByte() != 'D' || reader.ReadByte() != 'A' || reader.ReadByte() != 'M' || reader.ReadByte() != 'D') { throw new BadImageFormatException(); } // version byte major = reader.ReadByte(); byte minor = reader.ReadByte(); if (major != 0 || minor < 1 || minor > 2) { throw new NotSupportedException(); } // table sizes: int documentRowCount = reader.ReadInt32(); int methodSpanRowCount = reader.ReadInt32(); // blob heap sizes: int stringHeapSize = (minor == 1) ? reader.ReadInt32() : 0; int userStringHeapSize = (minor == 1) ? reader.ReadInt32() : 0; int guidHeapSize = reader.ReadInt32(); int blobHeapSize = reader.ReadInt32(); // TODO: check size ranges bool isBlobHeapSmall = blobHeapSize <= ushort.MaxValue; bool isGuidHeapSmall = guidHeapSize / GuidSize <= ushort.MaxValue; var documentsBuilder = ArrayBuilder<DynamicAnalysisDocument>.GetInstance(documentRowCount); for (int i = 0; i < documentRowCount; i++) { var name = MetadataTokens.BlobHandle(ReadReference(ref reader, isBlobHeapSmall)); var hashAlgorithm = MetadataTokens.GuidHandle(ReadReference(ref reader, isGuidHeapSmall)); var hash = MetadataTokens.BlobHandle(ReadReference(ref reader, isBlobHeapSmall)); documentsBuilder.Add(new DynamicAnalysisDocument(name, hashAlgorithm, hash)); } Documents = documentsBuilder.ToImmutableAndFree(); var methodsBuilder = ArrayBuilder<DynamicAnalysisMethod>.GetInstance(methodSpanRowCount); for (int i = 0; i < methodSpanRowCount; i++) { methodsBuilder.Add(new DynamicAnalysisMethod(MetadataTokens.BlobHandle(ReadReference(ref reader, isBlobHeapSmall)))); } Methods = methodsBuilder.ToImmutableAndFree(); int stringHeapOffset = reader.Offset; int userStringHeapOffset = stringHeapOffset + stringHeapSize; int guidHeapOffset = userStringHeapOffset + userStringHeapSize; int blobHeapOffset = guidHeapOffset + guidHeapSize; if (reader.Length != blobHeapOffset + blobHeapSize) { throw new BadImageFormatException(); } _guidHeapBlob = new Blob(buffer + guidHeapOffset, guidHeapSize); _blobHeapBlob = new Blob(buffer + blobHeapOffset, blobHeapSize); } public static DynamicAnalysisDataReader TryCreateFromPE(PEReader peReader, string resourceName) { // TODO: review all range checks, better error messages var mdReader = peReader.GetMetadataReader(); long offset = -1; foreach (var resourceHandle in mdReader.ManifestResources) { var resource = mdReader.GetManifestResource(resourceHandle); if (resource.Implementation.IsNil && resource.Attributes == ManifestResourceAttributes.Private && mdReader.StringComparer.Equals(resource.Name, resourceName)) { offset = resource.Offset; } } if (offset < 0) { return null; } var resourcesDir = peReader.PEHeaders.CorHeader.ResourcesDirectory; if (resourcesDir.Size < 0) { throw new BadImageFormatException(); } if (!peReader.PEHeaders.TryGetDirectoryOffset(resourcesDir, out var start)) { return null; } var peImage = peReader.GetEntireImage(); if (start >= peImage.Length - resourcesDir.Size) { throw new BadImageFormatException(); } byte* resourceStart = peImage.Pointer + start; int resourceSize = *(int*)resourceStart; if (resourceSize > resourcesDir.Size - sizeof(int)) { throw new BadImageFormatException(); } return new DynamicAnalysisDataReader(resourceStart + sizeof(int), resourceSize); } private static int ReadReference(ref BlobReader reader, bool smallRefSize) { return smallRefSize ? reader.ReadUInt16() : reader.ReadInt32(); } public ImmutableArray<DynamicAnalysisSpan> GetSpans(BlobHandle handle) { if (handle.IsNil) { return ImmutableArray<DynamicAnalysisSpan>.Empty; } var builder = ArrayBuilder<DynamicAnalysisSpan>.GetInstance(); var reader = GetBlobReader(handle); // header: int documentRowId = ReadDocumentRowId(ref reader); int previousStartLine = -1; ushort previousStartColumn = 0; // records: while (reader.RemainingBytes > 0) { ReadDeltaLinesAndColumns(ref reader, out var deltaLines, out var deltaColumns); // document: if (deltaLines == 0 && deltaColumns == 0) { documentRowId = ReadDocumentRowId(ref reader); continue; } int startLine; ushort startColumn; // delta Start Line & Column: if (previousStartLine < 0) { Debug.Assert(previousStartColumn == 0); startLine = ReadLine(ref reader); startColumn = ReadColumn(ref reader); } else { startLine = AddLines(previousStartLine, reader.ReadCompressedSignedInteger()); startColumn = AddColumns(previousStartColumn, reader.ReadCompressedSignedInteger()); } previousStartLine = startLine; previousStartColumn = startColumn; int endLine = AddLines(startLine, deltaLines); int endColumn = AddColumns(startColumn, deltaColumns); var linePositionSpan = new DynamicAnalysisSpan(documentRowId, startLine, startColumn, endLine, endColumn); builder.Add(linePositionSpan); } return builder.ToImmutableAndFree(); } //TODO: some of the helpers below should be provided by System.Reflection.Metadata private unsafe struct Blob { public readonly byte* Pointer; public readonly int Length; public Blob(byte* pointer, int length) { Pointer = pointer; Length = length; } } public Guid GetGuid(GuidHandle handle) { if (handle.IsNil) { return default(Guid); } int offset = (MetadataTokens.GetHeapOffset(handle) - 1) * GuidSize; if (offset + GuidSize > _guidHeapBlob.Length) { throw new BadImageFormatException(); } return *(Guid*)(_guidHeapBlob.Pointer + offset); } internal byte[] GetBytes(BlobHandle handle) { var reader = GetBlobReader(handle); return reader.ReadBytes(reader.Length); } private BlobReader GetBlobReader(BlobHandle handle) { int offset = MetadataTokens.GetHeapOffset(handle); byte* start = _blobHeapBlob.Pointer + offset; var reader = new BlobReader(start, _blobHeapBlob.Length - offset); int size = reader.ReadCompressedInteger(); return new BlobReader(start + reader.Offset, size); } public string GetDocumentName(BlobHandle handle) { var blobReader = GetBlobReader(handle); // Spec: separator is an ASCII encoded character in range [0x01, 0x7F], or byte 0 to represent an empty separator. int separator = blobReader.ReadByte(); if (separator > 0x7f) { throw new BadImageFormatException(string.Format("Invalid document name", separator)); } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; bool isFirstPart = true; while (blobReader.RemainingBytes > 0) { if (separator != 0 && !isFirstPart) { builder.Append((char)separator); } var partReader = GetBlobReader(blobReader.ReadBlobHandle()); // TODO: avoid allocating temp string (https://github.com/dotnet/corefx/issues/2102) builder.Append(partReader.ReadUTF8(partReader.Length)); isFirstPart = false; } return pooledBuilder.ToStringAndFree(); } private void ReadDeltaLinesAndColumns(ref BlobReader reader, out int deltaLines, out int deltaColumns) { deltaLines = reader.ReadCompressedInteger(); deltaColumns = (deltaLines == 0) ? reader.ReadCompressedInteger() : reader.ReadCompressedSignedInteger(); } private int ReadLine(ref BlobReader reader) { return reader.ReadCompressedInteger(); } private ushort ReadColumn(ref BlobReader reader) { int column = reader.ReadCompressedInteger(); if (column > ushort.MaxValue) { throw new BadImageFormatException("SequencePointValueOutOfRange"); } return (ushort)column; } private int AddLines(int value, int delta) { int result = unchecked(value + delta); if (result < 0) { throw new BadImageFormatException("SequencePointValueOutOfRange"); } return result; } private ushort AddColumns(ushort value, int delta) { int result = unchecked(value + delta); if (result < 0 || result >= ushort.MaxValue) { throw new BadImageFormatException("SequencePointValueOutOfRange"); } return (ushort)result; } private int ReadDocumentRowId(ref BlobReader reader) { int rowId = reader.ReadCompressedInteger(); if (rowId == 0) { throw new BadImageFormatException("Invalid handle"); } return rowId; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/MSBuildTest/Resources/Issue29122/Proj1/ClassLibrary1.vbproj
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion> </ProductVersion> <SchemaVersion> </SchemaVersion> <ProjectGuid>{F8AE35AB-1AC5-4381-BB3E-0645519695F5}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>ClassLibrary1</RootNamespace> <AssemblyName>ClassLibrary1</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile /> <RestorePackages>true</RestorePackages> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>On</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'"> <DebugSymbols>true</DebugSymbols> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>..\Dev\</OutputPath> <DebugType>full</DebugType> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'"> <DefineTrace>true</DefineTrace> <OutputPath>..\Dev\</OutputPath> <Optimize>true</Optimize> <DebugType>pdbonly</DebugType> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <ItemGroup> <Compile Include="Class1.vb" /> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion> </ProductVersion> <SchemaVersion> </SchemaVersion> <ProjectGuid>{F8AE35AB-1AC5-4381-BB3E-0645519695F5}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>ClassLibrary1</RootNamespace> <AssemblyName>ClassLibrary1</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile /> <RestorePackages>true</RestorePackages> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>On</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'"> <DebugSymbols>true</DebugSymbols> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>..\Dev\</OutputPath> <DebugType>full</DebugType> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'"> <DefineTrace>true</DefineTrace> <OutputPath>..\Dev\</OutputPath> <Optimize>true</Optimize> <DebugType>pdbonly</DebugType> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <ItemGroup> <Compile Include="Class1.vb" /> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> </Project>
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Completion/CompletionList.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The set of completions to present to the user. /// </summary> public sealed class CompletionList { private readonly bool _isExclusive; /// <summary> /// The completion items to present to the user. /// </summary> public ImmutableArray<CompletionItem> Items { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created. /// Individual <see cref="CompletionItem"/> spans may vary. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used instead.", error: true)] public TextSpan DefaultSpan { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> /// was created. /// /// The span identifies the text in the document that is used to filter the initial list /// presented to the user, and typically represents the region of the document that will /// be changed if this item is committed. /// </summary> public TextSpan Span { get; } /// <summary> /// The rules used to control behavior of the completion list shown to the user during typing. /// </summary> public CompletionRules Rules { get; } /// <summary> /// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode. /// Suggestion mode disables autoselection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually. /// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode. /// The item specified determines the text displayed and the description associated with it unless a different item is manually selected. /// No text is ever inserted when this item is completed, leaving the text the user typed instead. /// </summary> public CompletionItem SuggestionModeItem { get; } private CompletionList( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { Span = defaultSpan; Items = items.NullToEmpty(); Rules = rules ?? CompletionRules.Default; SuggestionModeItem = suggestionModeItem; _isExclusive = isExclusive; foreach (var item in Items) { item.Span = defaultSpan; } } /// <summary> /// Creates a new <see cref="CompletionList"/> instance. /// </summary> /// <param name="defaultSpan">The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.</param> /// <param name="items">The completion items to present to the user.</param> /// <param name="rules">The rules used to control behavior of the completion list shown to the user during typing.</param> /// <param name="suggestionModeItem">An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.</param> /// <returns></returns> public static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules = null, CompletionItem suggestionModeItem = null) { return Create(defaultSpan, items, rules, suggestionModeItem, isExclusive: false); } internal static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { return new CompletionList(defaultSpan, items, rules, suggestionModeItem, isExclusive); } private CompletionList With( Optional<TextSpan> span = default, Optional<ImmutableArray<CompletionItem>> items = default, Optional<CompletionRules> rules = default, Optional<CompletionItem> suggestionModeItem = default) { var newSpan = span.HasValue ? span.Value : Span; var newItems = items.HasValue ? items.Value : Items; var newRules = rules.HasValue ? rules.Value : Rules; var newSuggestionModeItem = suggestionModeItem.HasValue ? suggestionModeItem.Value : SuggestionModeItem; if (newSpan == Span && newItems == Items && newRules == Rules && newSuggestionModeItem == SuggestionModeItem) { return this; } else { return Create(newSpan, newItems, newRules, newSuggestionModeItem); } } /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="DefaultSpan"/> property changed. /// </summary> [Obsolete("Not used anymore. Use WithSpan instead.", error: true)] public CompletionList WithDefaultSpan(TextSpan span) => With(span: span); public CompletionList WithSpan(TextSpan span) => With(span: span); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Items"/> property changed. /// </summary> public CompletionList WithItems(ImmutableArray<CompletionItem> items) => With(items: items); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionList WithRules(CompletionRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="SuggestionModeItem"/> property changed. /// </summary> public CompletionList WithSuggestionModeItem(CompletionItem suggestionModeItem) => With(suggestionModeItem: suggestionModeItem); /// <summary> /// The default <see cref="CompletionList"/> returned when no items are found to populate the list. /// </summary> public static readonly CompletionList Empty = new( default, default, CompletionRules.Default, suggestionModeItem: null, isExclusive: false); internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly CompletionList _completionList; public TestAccessor(CompletionList completionList) => _completionList = completionList; internal bool IsExclusive => _completionList._isExclusive; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The set of completions to present to the user. /// </summary> public sealed class CompletionList { private readonly bool _isExclusive; /// <summary> /// The completion items to present to the user. /// </summary> public ImmutableArray<CompletionItem> Items { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created. /// Individual <see cref="CompletionItem"/> spans may vary. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used instead.", error: true)] public TextSpan DefaultSpan { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> /// was created. /// /// The span identifies the text in the document that is used to filter the initial list /// presented to the user, and typically represents the region of the document that will /// be changed if this item is committed. /// </summary> public TextSpan Span { get; } /// <summary> /// The rules used to control behavior of the completion list shown to the user during typing. /// </summary> public CompletionRules Rules { get; } /// <summary> /// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode. /// Suggestion mode disables autoselection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually. /// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode. /// The item specified determines the text displayed and the description associated with it unless a different item is manually selected. /// No text is ever inserted when this item is completed, leaving the text the user typed instead. /// </summary> public CompletionItem SuggestionModeItem { get; } private CompletionList( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { Span = defaultSpan; Items = items.NullToEmpty(); Rules = rules ?? CompletionRules.Default; SuggestionModeItem = suggestionModeItem; _isExclusive = isExclusive; foreach (var item in Items) { item.Span = defaultSpan; } } /// <summary> /// Creates a new <see cref="CompletionList"/> instance. /// </summary> /// <param name="defaultSpan">The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.</param> /// <param name="items">The completion items to present to the user.</param> /// <param name="rules">The rules used to control behavior of the completion list shown to the user during typing.</param> /// <param name="suggestionModeItem">An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.</param> /// <returns></returns> public static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules = null, CompletionItem suggestionModeItem = null) { return Create(defaultSpan, items, rules, suggestionModeItem, isExclusive: false); } internal static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { return new CompletionList(defaultSpan, items, rules, suggestionModeItem, isExclusive); } private CompletionList With( Optional<TextSpan> span = default, Optional<ImmutableArray<CompletionItem>> items = default, Optional<CompletionRules> rules = default, Optional<CompletionItem> suggestionModeItem = default) { var newSpan = span.HasValue ? span.Value : Span; var newItems = items.HasValue ? items.Value : Items; var newRules = rules.HasValue ? rules.Value : Rules; var newSuggestionModeItem = suggestionModeItem.HasValue ? suggestionModeItem.Value : SuggestionModeItem; if (newSpan == Span && newItems == Items && newRules == Rules && newSuggestionModeItem == SuggestionModeItem) { return this; } else { return Create(newSpan, newItems, newRules, newSuggestionModeItem); } } /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="DefaultSpan"/> property changed. /// </summary> [Obsolete("Not used anymore. Use WithSpan instead.", error: true)] public CompletionList WithDefaultSpan(TextSpan span) => With(span: span); public CompletionList WithSpan(TextSpan span) => With(span: span); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Items"/> property changed. /// </summary> public CompletionList WithItems(ImmutableArray<CompletionItem> items) => With(items: items); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionList WithRules(CompletionRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="SuggestionModeItem"/> property changed. /// </summary> public CompletionList WithSuggestionModeItem(CompletionItem suggestionModeItem) => With(suggestionModeItem: suggestionModeItem); /// <summary> /// The default <see cref="CompletionList"/> returned when no items are found to populate the list. /// </summary> public static readonly CompletionList Empty = new( default, default, CompletionRules.Default, suggestionModeItem: null, isExclusive: false); internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly CompletionList _completionList; public TestAccessor(CompletionList completionList) => _completionList = completionList; internal bool IsExclusive => _completionList._isExclusive; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IFromEndIndexOperation_IRangeOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IFromEndIndexOperation_IRangeOperation : SemanticModelTestBase { // The tests in this file right now are just to verify that we do not assert in the CFG builder. These need to be expanded. // https://github.com/dotnet/roslyn/issues/31545 [Fact] public void PatternIndexAndRangeIndexer() { var src = @" class C { public int Length => 0; public int this[int i] => i; public int Slice(int i, int j) => i; public void M() /*<bind*/{ _ = this[^0]; _ = this[0..]; }/*</bind>*/ }"; var comp = CreateCompilationWithIndexAndRange(src); const string expectedOperationTree = @" IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[^0];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[^0]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[^0]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^0') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[0..];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[0..]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[0..]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '0..') LeftOperand: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') RightOperand: null"; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, DiagnosticDescription.None); VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, DiagnosticDescription.None); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[^0];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[^0]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[^0]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^0') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[0..];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[0..]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[0..]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '0..') LeftOperand: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) (ImplicitUserDefined) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') RightOperand: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [Fact] public void FromEndIndexFlow_01() { var source = @" class Test { void M(int arg) /*<bind>*/{ var x = ^arg; }/*</bind>*/ }"; var compilation = CreateCompilationWithIndex(source); var expectedOperationTree = @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Index x IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = ^arg;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = ^arg') Declarators: IVariableDeclaratorOperation (Symbol: System.Index x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = ^arg') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ^arg') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') Initializer: null"; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Index x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Index, IsImplicit) (Syntax: 'x = ^arg') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Index, IsImplicit) (Syntax: 'x = ^arg') Right: IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } [Fact] public void RangeFlow_01() { var source = @" using System; class Test { void M(Index start, Index end) /*<bind>*/{ var a = start..end; var b = start..; var c = ..end; var d = ..; }/*</bind>*/ }"; var compilation = CreateCompilationWithIndexAndRange(source); var expectedOperationTree = @" IBlockOperation (4 statements, 4 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Range a Local_2: System.Range b Local_3: System.Range c Local_4: System.Range d IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var a = start..end;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = start..end') Declarators: IVariableDeclaratorOperation (Symbol: System.Range a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = start..end') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= start..end') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..end') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var b = start..;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var b = start..') Declarators: IVariableDeclaratorOperation (Symbol: System.Range b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = start..') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= start..') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: null Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c = ..end;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = ..end') Declarators: IVariableDeclaratorOperation (Symbol: System.Range c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = ..end') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ..end') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..end') LeftOperand: null RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var d = ..;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = ..') Declarators: IVariableDeclaratorOperation (Symbol: System.Range d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = ..') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ..') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..') LeftOperand: null RightOperand: null Initializer: null "; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Range a] [System.Range b] [System.Range c] [System.Range d] Block[B1] - Block Predecessors: [B0] Statements (4) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'a = start..end') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'a = start..end') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..end') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'b = start..') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'b = start..') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'c = ..end') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'c = ..end') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..end') LeftOperand: null RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'd = ..') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'd = ..') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..') LeftOperand: null RightOperand: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IFromEndIndexOperation_IRangeOperation : SemanticModelTestBase { // The tests in this file right now are just to verify that we do not assert in the CFG builder. These need to be expanded. // https://github.com/dotnet/roslyn/issues/31545 [Fact] public void PatternIndexAndRangeIndexer() { var src = @" class C { public int Length => 0; public int this[int i] => i; public int Slice(int i, int j) => i; public void M() /*<bind*/{ _ = this[^0]; _ = this[0..]; }/*</bind>*/ }"; var comp = CreateCompilationWithIndexAndRange(src); const string expectedOperationTree = @" IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[^0];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[^0]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[^0]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^0') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[0..];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[0..]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[0..]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '0..') LeftOperand: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') RightOperand: null"; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, DiagnosticDescription.None); VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, DiagnosticDescription.None); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[^0];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[^0]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[^0]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^0') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = this[0..];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = this[0..]') Left: IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_') Right: IOperation: (OperationKind.None, Type: null) (Syntax: 'this[0..]') Children(2): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '0..') LeftOperand: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Index System.Index.op_Implicit(System.Int32 value)) (OperationKind.Conversion, Type: System.Index, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Index System.Index.op_Implicit(System.Int32 value)) (ImplicitUserDefined) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') RightOperand: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [Fact] public void FromEndIndexFlow_01() { var source = @" class Test { void M(int arg) /*<bind>*/{ var x = ^arg; }/*</bind>*/ }"; var compilation = CreateCompilationWithIndex(source); var expectedOperationTree = @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Index x IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = ^arg;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = ^arg') Declarators: IVariableDeclaratorOperation (Symbol: System.Index x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = ^arg') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ^arg') IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') Initializer: null"; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Index x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Index, IsImplicit) (Syntax: 'x = ^arg') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Index, IsImplicit) (Syntax: 'x = ^arg') Right: IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } [Fact] public void RangeFlow_01() { var source = @" using System; class Test { void M(Index start, Index end) /*<bind>*/{ var a = start..end; var b = start..; var c = ..end; var d = ..; }/*</bind>*/ }"; var compilation = CreateCompilationWithIndexAndRange(source); var expectedOperationTree = @" IBlockOperation (4 statements, 4 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Range a Local_2: System.Range b Local_3: System.Range c Local_4: System.Range d IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var a = start..end;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = start..end') Declarators: IVariableDeclaratorOperation (Symbol: System.Range a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = start..end') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= start..end') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..end') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var b = start..;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var b = start..') Declarators: IVariableDeclaratorOperation (Symbol: System.Range b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = start..') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= start..') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: null Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c = ..end;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = ..end') Declarators: IVariableDeclaratorOperation (Symbol: System.Range c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = ..end') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ..end') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..end') LeftOperand: null RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var d = ..;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = ..') Declarators: IVariableDeclaratorOperation (Symbol: System.Range d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = ..') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ..') IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..') LeftOperand: null RightOperand: null Initializer: null "; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Range a] [System.Range b] [System.Range c] [System.Range d] Block[B1] - Block Predecessors: [B0] Statements (4) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'a = start..end') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'a = start..end') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..end') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'b = start..') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'b = start..') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: 'start..') LeftOperand: IParameterReferenceOperation: start (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'start') RightOperand: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'c = ..end') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'c = ..end') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..end') LeftOperand: null RightOperand: IParameterReferenceOperation: end (OperationKind.ParameterReference, Type: System.Index) (Syntax: 'end') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Range, IsImplicit) (Syntax: 'd = ..') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Range, IsImplicit) (Syntax: 'd = ..') Right: IRangeOperation (OperationKind.Range, Type: System.Range) (Syntax: '..') LeftOperand: null RightOperand: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/TryCastExpressionDocumentation.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class TryCastExpressionDocumentation Inherits AbstractCastExpressionDocumentation Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return { New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "TryCast"), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(") } End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class TryCastExpressionDocumentation Inherits AbstractCastExpressionDocumentation Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return { New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "TryCast"), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(") } End Get End Property End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/SymbolsTests/UseSiteErrors/CSharpErrors.dll
MZ@ !L!This program cannot be run in DOS mode. $PELhN! 3 @@ @P3K@`  H.text  `.rsrc@@@.reloc `@B3H"( *( *( *( *( *( *0 +*0 +* * *( *0 { +*"}*0 { +*"}*0 +*0 +* * *( *00{  ( t  |(+  -*00{  ( t  |(+  -*00{  ( t |(+  -*00{  ( t |(+  -*00{  ( t |(+  -*00{  ( t |(+  -*( *BSJB v4.0.30319l #~ #Strings#US#GUID#BlobW %3E<       < IM  ' dE zE   %2%>% H% [% p%  % % %%% %%%0% =% N% $^%-r%5% 9%@aP /$X /$` /$h /$p /$x /$/(5.W3c;/(5.W3c; /( 5B WHcR/(5XW_cR/(5jWyc m. y B X! /$"m."y"B"X# .$ B$ % X% .& ! &! B&"! X'%!/$( .( B( ) X) .* * B* X+/(,5$.W3.cR00! h1l! s2! 3! 4 " 5\" 6"/$7 h7 s8 9 : ; <  Y/a/$ /$ /$/$/$i/y/$!C. m.vACCCCC  !4Ta)a))19>CH)19>CH:9$%<;&'>=(A@) B C * D E + -.0/1234% (+J<Module>CSharpErrors.dllSubclass1CSharpErrorsSubclass2`1Subclass3ImplementingClass1ImplementingClass2`1ImplementingClass3ImplementingStruct1ImplementingStruct2`1ImplementingStruct3DelegateReturnType1DelegateReturnType2DelegateParameterType1DelegateParameterType2DelegateParameterType3`1ClassMethodsInterfaceMethodsClassPropertiesInterfacePropertiesEventDelegate`1ClassEventsInterfaceEventsUnavailableUnavailableClassTUnavailableClass`1mscorlibSystemObjectUnavailableInterfaceUnavailableInterface`1ValueTypeMulticastDelegate.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeReturnType1ReturnType2ParameterType1ParameterType2get_GetSet1set_GetSet1get_GetSet2set_GetSet2get_Get1get_Get2set_Set1set_Set2<GetSet1>k__BackingField<GetSet2>k__BackingFieldGetSet1GetSet2Get1Get2Set1Set2UnavailableDelegateEvent1add_Event1remove_Event1Event2add_Event2remove_Event2Event3add_Event3remove_Event3objectmethodcallbackresultuvalueSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeSystem.Runtime.InteropServicesStructLayoutAttributeLayoutKindCompilerGeneratedAttributeDelegateCombineSystem.ThreadingInterlockedCompareExchangeRemove /%PmGl~[  z\V4    !% !  !% !  !%    ! %  ! (() )P PP PPP  9AAA  ) ))) PPPP PPPPTWrapNonExceptionThrowsx33 3_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameCSharpErrors.dll(LegalCopyright LOriginalFilenameCSharpErrors.dll4ProductVersion0.0.0.08Assembly Version0.0.0.00 3
MZ@ !L!This program cannot be run in DOS mode. $PELhN! 3 @@ @P3K@`  H.text  `.rsrc@@@.reloc `@B3H"( *( *( *( *( *( *0 +*0 +* * *( *0 { +*"}*0 { +*"}*0 +*0 +* * *( *00{  ( t  |(+  -*00{  ( t  |(+  -*00{  ( t |(+  -*00{  ( t |(+  -*00{  ( t |(+  -*00{  ( t |(+  -*( *BSJB v4.0.30319l #~ #Strings#US#GUID#BlobW %3E<       < IM  ' dE zE   %2%>% H% [% p%  % % %%% %%%0% =% N% $^%-r%5% 9%@aP /$X /$` /$h /$p /$x /$/(5.W3c;/(5.W3c; /( 5B WHcR/(5XW_cR/(5jWyc m. y B X! /$"m."y"B"X# .$ B$ % X% .& ! &! B&"! X'%!/$( .( B( ) X) .* * B* X+/(,5$.W3.cR00! h1l! s2! 3! 4 " 5\" 6"/$7 h7 s8 9 : ; <  Y/a/$ /$ /$/$/$i/y/$!C. m.vACCCCC  !4Ta)a))19>CH)19>CH:9$%<;&'>=(A@) B C * D E + -.0/1234% (+J<Module>CSharpErrors.dllSubclass1CSharpErrorsSubclass2`1Subclass3ImplementingClass1ImplementingClass2`1ImplementingClass3ImplementingStruct1ImplementingStruct2`1ImplementingStruct3DelegateReturnType1DelegateReturnType2DelegateParameterType1DelegateParameterType2DelegateParameterType3`1ClassMethodsInterfaceMethodsClassPropertiesInterfacePropertiesEventDelegate`1ClassEventsInterfaceEventsUnavailableUnavailableClassTUnavailableClass`1mscorlibSystemObjectUnavailableInterfaceUnavailableInterface`1ValueTypeMulticastDelegate.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeReturnType1ReturnType2ParameterType1ParameterType2get_GetSet1set_GetSet1get_GetSet2set_GetSet2get_Get1get_Get2set_Set1set_Set2<GetSet1>k__BackingField<GetSet2>k__BackingFieldGetSet1GetSet2Get1Get2Set1Set2UnavailableDelegateEvent1add_Event1remove_Event1Event2add_Event2remove_Event2Event3add_Event3remove_Event3objectmethodcallbackresultuvalueSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeSystem.Runtime.InteropServicesStructLayoutAttributeLayoutKindCompilerGeneratedAttributeDelegateCombineSystem.ThreadingInterlockedCompareExchangeRemove /%PmGl~[  z\V4    !% !  !% !  !%    ! %  ! (() )P PP PPP  9AAA  ) ))) PPPP PPPPTWrapNonExceptionThrowsx33 3_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameCSharpErrors.dll(LegalCopyright LOriginalFilenameCSharpErrors.dll4ProductVersion0.0.0.08Assembly Version0.0.0.00 3
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextIndentBlockOperationAction.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextIndentBlockOperationAction { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; private readonly SyntaxNode _node; private readonly List<IndentBlockOperation> _list; public NextIndentBlockOperationAction( ImmutableArray<AbstractFormattingRule> formattingRules, int index, SyntaxNode node, List<IndentBlockOperation> list) { _formattingRules = formattingRules; _index = index; _node = node; _list = list; } private NextIndentBlockOperationAction NextAction => new(_formattingRules, _index + 1, _node, _list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 _formattingRules[_index].AddIndentBlockOperations(_list, _node, NextAction); return; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextIndentBlockOperationAction { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; private readonly SyntaxNode _node; private readonly List<IndentBlockOperation> _list; public NextIndentBlockOperationAction( ImmutableArray<AbstractFormattingRule> formattingRules, int index, SyntaxNode node, List<IndentBlockOperation> list) { _formattingRules = formattingRules; _index = index; _node = node; _list = list; } private NextIndentBlockOperationAction NextAction => new(_formattingRules, _index + 1, _node, _list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 _formattingRules[_index].AddIndentBlockOperations(_list, _node, NextAction); return; } } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.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 Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod <[UseExportProvider]> Partial Public Class ExtractMethodTests Protected Shared Async Function ExpectExtractMethodToFailAsync(codeWithMarker As XElement, Optional dontPutOutOrRefOnStruct As Boolean = True) As Tasks.Task Dim codeWithoutMarker As String = Nothing Dim textSpan As TextSpan MarkupTestFile.GetSpan(codeWithMarker.NormalizedValue, codeWithoutMarker, textSpan) Using workspace = TestWorkspace.CreateVisualBasic(codeWithoutMarker) Dim treeAfterExtractMethod = Await ExtractMethodAsync(workspace, workspace.Documents.First(), textSpan, succeeded:=False, dontPutOutOrRefOnStruct:=dontPutOutOrRefOnStruct) End Using End Function Private Shared Async Function NotSupported_ExtractMethodAsync(codeWithMarker As XElement) As Tasks.Task Dim codeWithoutMarker As String = Nothing Dim textSpan As TextSpan MarkupTestFile.GetSpan(codeWithMarker.NormalizedValue, codeWithoutMarker, textSpan) Using workspace = TestWorkspace.CreateVisualBasic(codeWithoutMarker) Assert.NotNull(Await Record.ExceptionAsync(Async Function() Dim tree = Await ExtractMethodAsync(workspace, workspace.Documents.First(), textSpan) End Function)) End Using End Function Protected Overloads Shared Async Function TestExtractMethodAsync( codeWithMarker As String, expected As String, Optional temporaryFailing As Boolean = False, Optional dontPutOutOrRefOnStruct As Boolean = True, Optional metadataReference As String = Nothing ) As Tasks.Task Dim metadataReferences = If(metadataReference Is Nothing, Array.Empty(Of String)(), New String() {metadataReference}) Using workspace = TestWorkspace.CreateVisualBasic(New String() {codeWithMarker}, metadataReferences:=metadataReferences, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim document = workspace.Documents.First() Dim subjectBuffer = document.GetTextBuffer() Dim textSpan = document.SelectedSpans.First() Dim tree = Await ExtractMethodAsync(workspace, workspace.Documents.First(), textSpan, dontPutOutOrRefOnStruct:=dontPutOutOrRefOnStruct) Using edit = subjectBuffer.CreateEdit() edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()) edit.Apply() End Using If temporaryFailing Then Assert.NotEqual(expected, subjectBuffer.CurrentSnapshot.GetText()) Else If expected = "" Then Assert.True(False, subjectBuffer.CurrentSnapshot.GetText()) End If Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText()) End If End Using End Function Protected Overloads Shared Async Function TestExtractMethodAsync( codeWithMarker As XElement, expected As XElement, Optional temporaryFailing As Boolean = False, Optional dontPutOutOrRefOnStruct As Boolean = True, Optional metadataReference As String = Nothing ) As Tasks.Task Await TestExtractMethodAsync(codeWithMarker.NormalizedValue, expected.NormalizedValue, temporaryFailing, dontPutOutOrRefOnStruct, metadataReference) End Function Private Shared Async Function ExtractMethodAsync( workspace As TestWorkspace, testDocument As TestHostDocument, textSpan As TextSpan, Optional succeeded As Boolean = True, Optional dontPutOutOrRefOnStruct As Boolean = True) As Tasks.Task(Of SyntaxNode) Dim snapshotSpan = textSpan.ToSnapshotSpan(testDocument.GetTextBuffer().CurrentSnapshot) Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id) Assert.NotNull(document) Dim originalOptions = Await document.GetOptionsAsync() Dim options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct) Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim validator = New VisualBasicSelectionValidator(sdocument, snapshotSpan.Span.ToTextSpan(), options) Dim selectedCode = Await validator.GetValidSelectionAsync(CancellationToken.None) If Not succeeded And selectedCode.Status.Failed() Then Return Nothing End If Assert.True(selectedCode.ContainsValidContext) ' extract method Dim extractor = New VisualBasicMethodExtractor(CType(selectedCode, VisualBasicSelectionResult)) Dim result = Await extractor.ExtractMethodAsync(CancellationToken.None) Assert.NotNull(result) Assert.Equal(succeeded, result.Succeeded OrElse result.SucceededWithSuggestion) Return Await result.Document.GetSyntaxRootAsync() End Function Private Shared Async Function TestSelectionAsync(codeWithMarker As XElement, Optional ByVal expectedFail As Boolean = False) As Tasks.Task Dim codeWithoutMarker As String = Nothing Dim namedSpans = CType(New Dictionary(Of String, ImmutableArray(Of TextSpan))(), IDictionary(Of String, ImmutableArray(Of TextSpan))) MarkupTestFile.GetSpans(codeWithMarker.NormalizedValue, codeWithoutMarker, namedSpans) Using workspace = TestWorkspace.CreateVisualBasic(codeWithoutMarker) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Assert.NotNull(document) Dim originalOptions = Await document.GetOptionsAsync() Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim validator = New VisualBasicSelectionValidator(sdocument, namedSpans("b").Single(), originalOptions) Dim result = Await validator.GetValidSelectionAsync(CancellationToken.None) If expectedFail Then Assert.True(result.Status.Failed(), "Selection didn't fail as expected") Else Assert.True(Microsoft.CodeAnalysis.ExtractMethod.Extensions.Succeeded(result.Status), "Selection wasn't expected to fail") End If If (Microsoft.CodeAnalysis.ExtractMethod.Extensions.Succeeded(result.Status) OrElse result.Status.Flag.HasBestEffort()) AndAlso result.Status.Flag.HasSuggestion() Then Assert.Equal(namedSpans("r").Single(), result.FinalSpan) End If End Using End Function Private Shared Async Function TestInMethodAsync(codeWithMarker As XElement, Optional ByVal expectedFail As Boolean = False) As Tasks.Task Dim markupWithMarker = <text>Class C Sub S<%= codeWithMarker.Value %> End Sub End Class</text> Await TestSelectionAsync(markupWithMarker, expectedFail) End Function Private Shared Async Function IterateAllAsync(code As String) As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic(code) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Assert.NotNull(document) Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim root = Await document.GetSyntaxRootAsync() Dim iterator = root.DescendantNodesAndSelf() Dim originalOptions = Await document.GetOptionsAsync() For Each node In iterator Try Dim validator = New VisualBasicSelectionValidator(sdocument, node.Span, originalOptions) Dim result = Await validator.GetValidSelectionAsync(CancellationToken.None) ' check the obvious case If Not (TypeOf node Is ExpressionSyntax) AndAlso (Not node.UnderValidContext()) Then Assert.True(result.Status.Flag.Failed()) End If Catch e1 As ArgumentException ' catch and ignore unknown issue. currently control flow analysis engine doesn't support field initializer. End Try Next node End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod <[UseExportProvider]> Partial Public Class ExtractMethodTests Protected Shared Async Function ExpectExtractMethodToFailAsync(codeWithMarker As XElement, Optional dontPutOutOrRefOnStruct As Boolean = True) As Tasks.Task Dim codeWithoutMarker As String = Nothing Dim textSpan As TextSpan MarkupTestFile.GetSpan(codeWithMarker.NormalizedValue, codeWithoutMarker, textSpan) Using workspace = TestWorkspace.CreateVisualBasic(codeWithoutMarker) Dim treeAfterExtractMethod = Await ExtractMethodAsync(workspace, workspace.Documents.First(), textSpan, succeeded:=False, dontPutOutOrRefOnStruct:=dontPutOutOrRefOnStruct) End Using End Function Private Shared Async Function NotSupported_ExtractMethodAsync(codeWithMarker As XElement) As Tasks.Task Dim codeWithoutMarker As String = Nothing Dim textSpan As TextSpan MarkupTestFile.GetSpan(codeWithMarker.NormalizedValue, codeWithoutMarker, textSpan) Using workspace = TestWorkspace.CreateVisualBasic(codeWithoutMarker) Assert.NotNull(Await Record.ExceptionAsync(Async Function() Dim tree = Await ExtractMethodAsync(workspace, workspace.Documents.First(), textSpan) End Function)) End Using End Function Protected Overloads Shared Async Function TestExtractMethodAsync( codeWithMarker As String, expected As String, Optional temporaryFailing As Boolean = False, Optional dontPutOutOrRefOnStruct As Boolean = True, Optional metadataReference As String = Nothing ) As Tasks.Task Dim metadataReferences = If(metadataReference Is Nothing, Array.Empty(Of String)(), New String() {metadataReference}) Using workspace = TestWorkspace.CreateVisualBasic(New String() {codeWithMarker}, metadataReferences:=metadataReferences, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim document = workspace.Documents.First() Dim subjectBuffer = document.GetTextBuffer() Dim textSpan = document.SelectedSpans.First() Dim tree = Await ExtractMethodAsync(workspace, workspace.Documents.First(), textSpan, dontPutOutOrRefOnStruct:=dontPutOutOrRefOnStruct) Using edit = subjectBuffer.CreateEdit() edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()) edit.Apply() End Using If temporaryFailing Then Assert.NotEqual(expected, subjectBuffer.CurrentSnapshot.GetText()) Else If expected = "" Then Assert.True(False, subjectBuffer.CurrentSnapshot.GetText()) End If Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText()) End If End Using End Function Protected Overloads Shared Async Function TestExtractMethodAsync( codeWithMarker As XElement, expected As XElement, Optional temporaryFailing As Boolean = False, Optional dontPutOutOrRefOnStruct As Boolean = True, Optional metadataReference As String = Nothing ) As Tasks.Task Await TestExtractMethodAsync(codeWithMarker.NormalizedValue, expected.NormalizedValue, temporaryFailing, dontPutOutOrRefOnStruct, metadataReference) End Function Private Shared Async Function ExtractMethodAsync( workspace As TestWorkspace, testDocument As TestHostDocument, textSpan As TextSpan, Optional succeeded As Boolean = True, Optional dontPutOutOrRefOnStruct As Boolean = True) As Tasks.Task(Of SyntaxNode) Dim snapshotSpan = textSpan.ToSnapshotSpan(testDocument.GetTextBuffer().CurrentSnapshot) Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id) Assert.NotNull(document) Dim originalOptions = Await document.GetOptionsAsync() Dim options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct) Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim validator = New VisualBasicSelectionValidator(sdocument, snapshotSpan.Span.ToTextSpan(), options) Dim selectedCode = Await validator.GetValidSelectionAsync(CancellationToken.None) If Not succeeded And selectedCode.Status.Failed() Then Return Nothing End If Assert.True(selectedCode.ContainsValidContext) ' extract method Dim extractor = New VisualBasicMethodExtractor(CType(selectedCode, VisualBasicSelectionResult)) Dim result = Await extractor.ExtractMethodAsync(CancellationToken.None) Assert.NotNull(result) Assert.Equal(succeeded, result.Succeeded OrElse result.SucceededWithSuggestion) Return Await result.Document.GetSyntaxRootAsync() End Function Private Shared Async Function TestSelectionAsync(codeWithMarker As XElement, Optional ByVal expectedFail As Boolean = False) As Tasks.Task Dim codeWithoutMarker As String = Nothing Dim namedSpans = CType(New Dictionary(Of String, ImmutableArray(Of TextSpan))(), IDictionary(Of String, ImmutableArray(Of TextSpan))) MarkupTestFile.GetSpans(codeWithMarker.NormalizedValue, codeWithoutMarker, namedSpans) Using workspace = TestWorkspace.CreateVisualBasic(codeWithoutMarker) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Assert.NotNull(document) Dim originalOptions = Await document.GetOptionsAsync() Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim validator = New VisualBasicSelectionValidator(sdocument, namedSpans("b").Single(), originalOptions) Dim result = Await validator.GetValidSelectionAsync(CancellationToken.None) If expectedFail Then Assert.True(result.Status.Failed(), "Selection didn't fail as expected") Else Assert.True(Microsoft.CodeAnalysis.ExtractMethod.Extensions.Succeeded(result.Status), "Selection wasn't expected to fail") End If If (Microsoft.CodeAnalysis.ExtractMethod.Extensions.Succeeded(result.Status) OrElse result.Status.Flag.HasBestEffort()) AndAlso result.Status.Flag.HasSuggestion() Then Assert.Equal(namedSpans("r").Single(), result.FinalSpan) End If End Using End Function Private Shared Async Function TestInMethodAsync(codeWithMarker As XElement, Optional ByVal expectedFail As Boolean = False) As Tasks.Task Dim markupWithMarker = <text>Class C Sub S<%= codeWithMarker.Value %> End Sub End Class</text> Await TestSelectionAsync(markupWithMarker, expectedFail) End Function Private Shared Async Function IterateAllAsync(code As String) As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic(code) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Assert.NotNull(document) Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim root = Await document.GetSyntaxRootAsync() Dim iterator = root.DescendantNodesAndSelf() Dim originalOptions = Await document.GetOptionsAsync() For Each node In iterator Try Dim validator = New VisualBasicSelectionValidator(sdocument, node.Span, originalOptions) Dim result = Await validator.GetValidSelectionAsync(CancellationToken.None) ' check the obvious case If Not (TypeOf node Is ExpressionSyntax) AndAlso (Not node.UnderValidContext()) Then Assert.True(result.Status.Flag.Failed()) End If Catch e1 As ArgumentException ' catch and ignore unknown issue. currently control flow analysis engine doesn't support field initializer. End Try Next node End Using End Function End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxTree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> where TCompilationUnitSyntax : TSyntaxNode { public readonly VirtualCharSequence Text; public readonly TCompilationUnitSyntax Root; public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics; protected EmbeddedSyntaxTree( VirtualCharSequence text, TCompilationUnitSyntax root, ImmutableArray<EmbeddedDiagnostic> diagnostics) { Text = text; Root = root; Diagnostics = diagnostics; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> where TCompilationUnitSyntax : TSyntaxNode { public readonly VirtualCharSequence Text; public readonly TCompilationUnitSyntax Root; public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics; protected EmbeddedSyntaxTree( VirtualCharSequence text, TCompilationUnitSyntax root, ImmutableArray<EmbeddedDiagnostic> diagnostics) { Text = text; Root = root; Diagnostics = diagnostics; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle { internal static class TypeStyleHelper { public static bool IsBuiltInType(ITypeSymbol type) => type?.IsSpecialType() == true; /// <summary> /// Analyzes if type information is obvious to the reader by simply looking at the assignment expression. /// </summary> /// <remarks> /// <paramref name="typeInDeclaration"/> accepts null, to be able to cater to codegen features /// that are about to generate a local declaration and do not have this information to pass in. /// Things (like analyzers) that do have a local declaration already, should pass this in. /// </remarks> public static bool IsTypeApparentInAssignmentExpression( UseVarPreference stylePreferences, ExpressionSyntax initializerExpression, SemanticModel semanticModel, ITypeSymbol? typeInDeclaration, CancellationToken cancellationToken) { // tuple literals if (initializerExpression.IsKind(SyntaxKind.TupleExpression, out TupleExpressionSyntax? tuple)) { if (typeInDeclaration == null || !typeInDeclaration.IsTupleType) { return false; } var tupleType = (INamedTypeSymbol)typeInDeclaration; if (tupleType.TupleElements.Length != tuple.Arguments.Count) { return false; } for (int i = 0, n = tuple.Arguments.Count; i < n; i++) { var argument = tuple.Arguments[i]; var tupleElementType = tupleType.TupleElements[i].Type; if (!IsTypeApparentInAssignmentExpression( stylePreferences, argument.Expression, semanticModel, tupleElementType, cancellationToken)) { return false; } } return true; } // default(type) if (initializerExpression.IsKind(SyntaxKind.DefaultExpression)) { return true; } // literals, use var if options allow usage here. if (initializerExpression.IsAnyLiteralExpression()) { return stylePreferences.HasFlag(UseVarPreference.ForBuiltInTypes); } // constructor invocations cases: // = new type(); if (initializerExpression.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ArrayCreationExpression) && !initializerExpression.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) { return true; } // explicit conversion cases: // (type)expr, expr is type, expr as type if (initializerExpression.IsKind(SyntaxKind.CastExpression) || initializerExpression.IsKind(SyntaxKind.IsExpression) || initializerExpression.IsKind(SyntaxKind.AsExpression)) { return true; } // other Conversion cases: // a. conversion with helpers like: int.Parse methods // b. types that implement IConvertible and then invoking .ToType() // c. System.Convert.ToType() var memberName = GetRightmostInvocationExpression(initializerExpression).GetRightmostName(); if (memberName == null) { return false; } if (!(semanticModel.GetSymbolInfo(memberName, cancellationToken).Symbol is IMethodSymbol methodSymbol)) { return false; } if (memberName.IsRightSideOfDot()) { var containingTypeName = memberName.GetLeftSideOfDot(); return IsPossibleCreationOrConversionMethod(methodSymbol, typeInDeclaration, semanticModel, containingTypeName, cancellationToken); } return false; } private static bool IsPossibleCreationOrConversionMethod(IMethodSymbol methodSymbol, ITypeSymbol? typeInDeclaration, SemanticModel semanticModel, ExpressionSyntax containingTypeName, CancellationToken cancellationToken) { if (methodSymbol.ReturnsVoid) { return false; } var containingType = semanticModel.GetTypeInfo(containingTypeName, cancellationToken).Type; // The containing type was determined from an expression of the form ContainingType.MemberName, and the // caller verifies that MemberName resolves to a method symbol. Contract.ThrowIfNull(containingType); return IsPossibleCreationMethod(methodSymbol, typeInDeclaration, containingType) || IsPossibleConversionMethod(methodSymbol); } /// <summary> /// Looks for types that have static methods that return the same type as the container. /// e.g: int.Parse, XElement.Load, Tuple.Create etc. /// </summary> private static bool IsPossibleCreationMethod(IMethodSymbol methodSymbol, ITypeSymbol? typeInDeclaration, ITypeSymbol containingType) { if (!methodSymbol.IsStatic) { return false; } return IsContainerTypeEqualToReturnType(methodSymbol, typeInDeclaration, containingType); } /// <summary> /// If we have a method ToXXX and its return type is also XXX, then type name is apparent /// e.g: Convert.ToString. /// </summary> private static bool IsPossibleConversionMethod(IMethodSymbol methodSymbol) { var returnType = methodSymbol.ReturnType; var returnTypeName = returnType.IsNullable() ? returnType.GetTypeArguments().First().Name : returnType.Name; return methodSymbol.Name.Equals("To" + returnTypeName, StringComparison.Ordinal); } /// <remarks> /// If there are type arguments on either side of assignment, we match type names instead of type equality /// to account for inferred generic type arguments. /// e.g: Tuple.Create(0, true) returns Tuple&lt;X,y&gt; which isn't the same as type Tuple. /// otherwise, we match for type equivalence /// </remarks> private static bool IsContainerTypeEqualToReturnType(IMethodSymbol methodSymbol, ITypeSymbol? typeInDeclaration, ITypeSymbol containingType) { var returnType = UnwrapTupleType(methodSymbol.ReturnType); if (UnwrapTupleType(typeInDeclaration)?.GetTypeArguments().Length > 0 || containingType.GetTypeArguments().Length > 0) { return UnwrapTupleType(containingType).Name.Equals(returnType.Name); } else { return UnwrapTupleType(containingType).Equals(returnType); } } [return: NotNullIfNotNull("symbol")] private static ITypeSymbol? UnwrapTupleType(ITypeSymbol? symbol) { if (symbol is null) return null; if (!(symbol is INamedTypeSymbol namedTypeSymbol)) return symbol; return namedTypeSymbol.TupleUnderlyingType ?? symbol; } private static ExpressionSyntax GetRightmostInvocationExpression(ExpressionSyntax node) { if (node is AwaitExpressionSyntax awaitExpression && awaitExpression.Expression != null) { return GetRightmostInvocationExpression(awaitExpression.Expression); } if (node is InvocationExpressionSyntax invocationExpression && invocationExpression.Expression != null) { return GetRightmostInvocationExpression(invocationExpression.Expression); } if (node is ConditionalAccessExpressionSyntax conditional) { return GetRightmostInvocationExpression(conditional.WhenNotNull); } return node; } public static bool IsPredefinedType(TypeSyntax type) { return type is PredefinedTypeSyntax predefinedType ? SyntaxFacts.IsPredefinedType(predefinedType.Keyword.Kind()) : 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle { internal static class TypeStyleHelper { public static bool IsBuiltInType(ITypeSymbol type) => type?.IsSpecialType() == true; /// <summary> /// Analyzes if type information is obvious to the reader by simply looking at the assignment expression. /// </summary> /// <remarks> /// <paramref name="typeInDeclaration"/> accepts null, to be able to cater to codegen features /// that are about to generate a local declaration and do not have this information to pass in. /// Things (like analyzers) that do have a local declaration already, should pass this in. /// </remarks> public static bool IsTypeApparentInAssignmentExpression( UseVarPreference stylePreferences, ExpressionSyntax initializerExpression, SemanticModel semanticModel, ITypeSymbol? typeInDeclaration, CancellationToken cancellationToken) { // tuple literals if (initializerExpression.IsKind(SyntaxKind.TupleExpression, out TupleExpressionSyntax? tuple)) { if (typeInDeclaration == null || !typeInDeclaration.IsTupleType) { return false; } var tupleType = (INamedTypeSymbol)typeInDeclaration; if (tupleType.TupleElements.Length != tuple.Arguments.Count) { return false; } for (int i = 0, n = tuple.Arguments.Count; i < n; i++) { var argument = tuple.Arguments[i]; var tupleElementType = tupleType.TupleElements[i].Type; if (!IsTypeApparentInAssignmentExpression( stylePreferences, argument.Expression, semanticModel, tupleElementType, cancellationToken)) { return false; } } return true; } // default(type) if (initializerExpression.IsKind(SyntaxKind.DefaultExpression)) { return true; } // literals, use var if options allow usage here. if (initializerExpression.IsAnyLiteralExpression()) { return stylePreferences.HasFlag(UseVarPreference.ForBuiltInTypes); } // constructor invocations cases: // = new type(); if (initializerExpression.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ArrayCreationExpression) && !initializerExpression.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) { return true; } // explicit conversion cases: // (type)expr, expr is type, expr as type if (initializerExpression.IsKind(SyntaxKind.CastExpression) || initializerExpression.IsKind(SyntaxKind.IsExpression) || initializerExpression.IsKind(SyntaxKind.AsExpression)) { return true; } // other Conversion cases: // a. conversion with helpers like: int.Parse methods // b. types that implement IConvertible and then invoking .ToType() // c. System.Convert.ToType() var memberName = GetRightmostInvocationExpression(initializerExpression).GetRightmostName(); if (memberName == null) { return false; } if (!(semanticModel.GetSymbolInfo(memberName, cancellationToken).Symbol is IMethodSymbol methodSymbol)) { return false; } if (memberName.IsRightSideOfDot()) { var containingTypeName = memberName.GetLeftSideOfDot(); return IsPossibleCreationOrConversionMethod(methodSymbol, typeInDeclaration, semanticModel, containingTypeName, cancellationToken); } return false; } private static bool IsPossibleCreationOrConversionMethod(IMethodSymbol methodSymbol, ITypeSymbol? typeInDeclaration, SemanticModel semanticModel, ExpressionSyntax containingTypeName, CancellationToken cancellationToken) { if (methodSymbol.ReturnsVoid) { return false; } var containingType = semanticModel.GetTypeInfo(containingTypeName, cancellationToken).Type; // The containing type was determined from an expression of the form ContainingType.MemberName, and the // caller verifies that MemberName resolves to a method symbol. Contract.ThrowIfNull(containingType); return IsPossibleCreationMethod(methodSymbol, typeInDeclaration, containingType) || IsPossibleConversionMethod(methodSymbol); } /// <summary> /// Looks for types that have static methods that return the same type as the container. /// e.g: int.Parse, XElement.Load, Tuple.Create etc. /// </summary> private static bool IsPossibleCreationMethod(IMethodSymbol methodSymbol, ITypeSymbol? typeInDeclaration, ITypeSymbol containingType) { if (!methodSymbol.IsStatic) { return false; } return IsContainerTypeEqualToReturnType(methodSymbol, typeInDeclaration, containingType); } /// <summary> /// If we have a method ToXXX and its return type is also XXX, then type name is apparent /// e.g: Convert.ToString. /// </summary> private static bool IsPossibleConversionMethod(IMethodSymbol methodSymbol) { var returnType = methodSymbol.ReturnType; var returnTypeName = returnType.IsNullable() ? returnType.GetTypeArguments().First().Name : returnType.Name; return methodSymbol.Name.Equals("To" + returnTypeName, StringComparison.Ordinal); } /// <remarks> /// If there are type arguments on either side of assignment, we match type names instead of type equality /// to account for inferred generic type arguments. /// e.g: Tuple.Create(0, true) returns Tuple&lt;X,y&gt; which isn't the same as type Tuple. /// otherwise, we match for type equivalence /// </remarks> private static bool IsContainerTypeEqualToReturnType(IMethodSymbol methodSymbol, ITypeSymbol? typeInDeclaration, ITypeSymbol containingType) { var returnType = UnwrapTupleType(methodSymbol.ReturnType); if (UnwrapTupleType(typeInDeclaration)?.GetTypeArguments().Length > 0 || containingType.GetTypeArguments().Length > 0) { return UnwrapTupleType(containingType).Name.Equals(returnType.Name); } else { return UnwrapTupleType(containingType).Equals(returnType); } } [return: NotNullIfNotNull("symbol")] private static ITypeSymbol? UnwrapTupleType(ITypeSymbol? symbol) { if (symbol is null) return null; if (!(symbol is INamedTypeSymbol namedTypeSymbol)) return symbol; return namedTypeSymbol.TupleUnderlyingType ?? symbol; } private static ExpressionSyntax GetRightmostInvocationExpression(ExpressionSyntax node) { if (node is AwaitExpressionSyntax awaitExpression && awaitExpression.Expression != null) { return GetRightmostInvocationExpression(awaitExpression.Expression); } if (node is InvocationExpressionSyntax invocationExpression && invocationExpression.Expression != null) { return GetRightmostInvocationExpression(invocationExpression.Expression); } if (node is ConditionalAccessExpressionSyntax conditional) { return GetRightmostInvocationExpression(conditional.WhenNotNull); } return node; } public static bool IsPredefinedType(TypeSyntax type) { return type is PredefinedTypeSyntax predefinedType ? SyntaxFacts.IsPredefinedType(predefinedType.Keyword.Kind()) : false; } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSymbolDeclarationService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ISymbolDeclarationService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSymbolDeclarationService Implements ISymbolDeclarationService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub ''' <summary> ''' Get the declaring syntax node for a Symbol. Unlike the DeclaringSyntaxReferences property, ''' this function always returns a block syntax, if there is one. ''' </summary> Public Function GetDeclarations(symbol As ISymbol) As ImmutableArray(Of SyntaxReference) Implements ISymbolDeclarationService.GetDeclarations Return If(symbol Is Nothing, ImmutableArray(Of SyntaxReference).Empty, symbol.DeclaringSyntaxReferences.SelectAsArray(Of SyntaxReference)( Function(r) New BlockSyntaxReference(r))) End Function Private Class BlockSyntaxReference Inherits SyntaxReference Private ReadOnly _reference As SyntaxReference Public Sub New(reference As SyntaxReference) _reference = reference End Sub Public Overrides Function GetSyntax(Optional cancellationToken As CancellationToken = Nothing) As SyntaxNode Return DirectCast(GetBlockFromBegin(_reference.GetSyntax(cancellationToken)), VisualBasicSyntaxNode) End Function Public Overrides Async Function GetSyntaxAsync(Optional cancellationToken As CancellationToken = Nothing) As Task(Of SyntaxNode) Dim node = Await _reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(False) Return GetBlockFromBegin(node) End Function Public Overrides ReadOnly Property Span As TextSpan Get Return _reference.Span End Get End Property Public Overrides ReadOnly Property SyntaxTree As SyntaxTree Get Return _reference.SyntaxTree End Get End Property End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ISymbolDeclarationService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSymbolDeclarationService Implements ISymbolDeclarationService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub ''' <summary> ''' Get the declaring syntax node for a Symbol. Unlike the DeclaringSyntaxReferences property, ''' this function always returns a block syntax, if there is one. ''' </summary> Public Function GetDeclarations(symbol As ISymbol) As ImmutableArray(Of SyntaxReference) Implements ISymbolDeclarationService.GetDeclarations Return If(symbol Is Nothing, ImmutableArray(Of SyntaxReference).Empty, symbol.DeclaringSyntaxReferences.SelectAsArray(Of SyntaxReference)( Function(r) New BlockSyntaxReference(r))) End Function Private Class BlockSyntaxReference Inherits SyntaxReference Private ReadOnly _reference As SyntaxReference Public Sub New(reference As SyntaxReference) _reference = reference End Sub Public Overrides Function GetSyntax(Optional cancellationToken As CancellationToken = Nothing) As SyntaxNode Return DirectCast(GetBlockFromBegin(_reference.GetSyntax(cancellationToken)), VisualBasicSyntaxNode) End Function Public Overrides Async Function GetSyntaxAsync(Optional cancellationToken As CancellationToken = Nothing) As Task(Of SyntaxNode) Dim node = Await _reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(False) Return GetBlockFromBegin(node) End Function Public Overrides ReadOnly Property Span As TextSpan Get Return _reference.Span End Get End Property Public Overrides ReadOnly Property SyntaxTree As SyntaxTree Get Return _reference.SyntaxTree End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/ExtractClass/ExtractClassDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { /// <summary> /// Interaction logic for ExtractClassDialog.xaml /// </summary> internal partial class ExtractClassDialog : DialogWindow { public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string SelectMembers => ServicesVSResources.Select_members_colon; public string ExtractClassTitle => ServicesVSResources.Extract_Base_Class; public ExtractClassViewModel ViewModel { get; } public MemberSelection MemberSelectionControl { get; } public ExtractClassDialog(ExtractClassViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = 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.Windows; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { /// <summary> /// Interaction logic for ExtractClassDialog.xaml /// </summary> internal partial class ExtractClassDialog : DialogWindow { public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string SelectMembers => ServicesVSResources.Select_members_colon; public string ExtractClassTitle => ServicesVSResources.Extract_Base_Class; public ExtractClassViewModel ViewModel { get; } public MemberSelection MemberSelectionControl { get; } public ExtractClassDialog(ExtractClassViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/CSharpTest/PrintOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests { public class PrintOptionsTests : ObjectFormatterTestBase { private static readonly ObjectFormatter s_formatter = new TestCSharpObjectFormatter(); [Fact] public void NullOptions() { Assert.Throws<ArgumentNullException>(() => s_formatter.FormatObject("hello", options: null)); } [Fact] public void InvalidNumberRadix() { Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().NumberRadix = 3); } [Fact] public void InvalidMemberDisplayFormat() { Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MemberDisplayFormat = (MemberDisplayFormat)(-1)); } [Fact] public void InvalidMaximumOutputLength() { Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = -1); Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = 0); } [Fact] public void ValidNumberRadix() { var formatter = new TestCSharpObjectFormatter(includeCodePoints: true); var options = new PrintOptions(); options.NumberRadix = 10; Assert.Equal("10", formatter.FormatObject(10, options)); Assert.Equal("int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", formatter.FormatObject(new int[10], options)); Assert.Equal(@"16 '\u0010'", formatter.FormatObject('\u0010', options)); options.NumberRadix = 16; Assert.Equal("0x0000000a", formatter.FormatObject(10, options)); Assert.Equal("int[0x0000000a] { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }", formatter.FormatObject(new int[10], options)); Assert.Equal(@"0x0010 '\u0010'", formatter.FormatObject('\u0010', options)); } [Fact] public void ValidMemberDisplayFormat() { var options = new PrintOptions(); options.MemberDisplayFormat = MemberDisplayFormat.Hidden; Assert.Equal("PrintOptions", s_formatter.FormatObject(options, options)); options.MemberDisplayFormat = MemberDisplayFormat.SingleLine; Assert.Equal("PrintOptions { Ellipsis=\"...\", EscapeNonPrintableCharacters=true, MaximumOutputLength=1024, MemberDisplayFormat=SingleLine, NumberRadix=10 }", s_formatter.FormatObject(options, options)); options.MemberDisplayFormat = MemberDisplayFormat.SeparateLines; Assert.Equal(@"PrintOptions { Ellipsis: ""..."", EscapeNonPrintableCharacters: true, MaximumOutputLength: 1024, MemberDisplayFormat: SeparateLines, NumberRadix: 10, _maximumOutputLength: 1024, _memberDisplayFormat: SeparateLines, _numberRadix: 10 } ", s_formatter.FormatObject(options, options)); } [Fact] public void ValidEscapeNonPrintableCharacters() { var options = new PrintOptions(); options.EscapeNonPrintableCharacters = true; Assert.Equal(@"""\t""", s_formatter.FormatObject("\t", options)); Assert.Equal(@"'\t'", s_formatter.FormatObject('\t', options)); options.EscapeNonPrintableCharacters = false; Assert.Equal("\"\t\"", s_formatter.FormatObject("\t", options)); Assert.Equal("'\t'", s_formatter.FormatObject('\t', options)); } [Fact] public void ValidMaximumOutputLength() { var options = new PrintOptions(); options.MaximumOutputLength = 1; Assert.Equal("1...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 2; Assert.Equal("12...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 3; Assert.Equal("123...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 4; Assert.Equal("1234...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 5; Assert.Equal("12345...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 6; Assert.Equal("123456", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 7; Assert.Equal("123456", s_formatter.FormatObject(123456, options)); } [Fact] public void ValidEllipsis() { var options = new PrintOptions(); options.MaximumOutputLength = 1; options.Ellipsis = "."; Assert.Equal("1.", s_formatter.FormatObject(123456, options)); options.Ellipsis = ".."; Assert.Equal("1..", s_formatter.FormatObject(123456, options)); options.Ellipsis = ""; Assert.Equal("1", s_formatter.FormatObject(123456, options)); options.Ellipsis = null; Assert.Equal("1", s_formatter.FormatObject(123456, options)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests { public class PrintOptionsTests : ObjectFormatterTestBase { private static readonly ObjectFormatter s_formatter = new TestCSharpObjectFormatter(); [Fact] public void NullOptions() { Assert.Throws<ArgumentNullException>(() => s_formatter.FormatObject("hello", options: null)); } [Fact] public void InvalidNumberRadix() { Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().NumberRadix = 3); } [Fact] public void InvalidMemberDisplayFormat() { Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MemberDisplayFormat = (MemberDisplayFormat)(-1)); } [Fact] public void InvalidMaximumOutputLength() { Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = -1); Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = 0); } [Fact] public void ValidNumberRadix() { var formatter = new TestCSharpObjectFormatter(includeCodePoints: true); var options = new PrintOptions(); options.NumberRadix = 10; Assert.Equal("10", formatter.FormatObject(10, options)); Assert.Equal("int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", formatter.FormatObject(new int[10], options)); Assert.Equal(@"16 '\u0010'", formatter.FormatObject('\u0010', options)); options.NumberRadix = 16; Assert.Equal("0x0000000a", formatter.FormatObject(10, options)); Assert.Equal("int[0x0000000a] { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }", formatter.FormatObject(new int[10], options)); Assert.Equal(@"0x0010 '\u0010'", formatter.FormatObject('\u0010', options)); } [Fact] public void ValidMemberDisplayFormat() { var options = new PrintOptions(); options.MemberDisplayFormat = MemberDisplayFormat.Hidden; Assert.Equal("PrintOptions", s_formatter.FormatObject(options, options)); options.MemberDisplayFormat = MemberDisplayFormat.SingleLine; Assert.Equal("PrintOptions { Ellipsis=\"...\", EscapeNonPrintableCharacters=true, MaximumOutputLength=1024, MemberDisplayFormat=SingleLine, NumberRadix=10 }", s_formatter.FormatObject(options, options)); options.MemberDisplayFormat = MemberDisplayFormat.SeparateLines; Assert.Equal(@"PrintOptions { Ellipsis: ""..."", EscapeNonPrintableCharacters: true, MaximumOutputLength: 1024, MemberDisplayFormat: SeparateLines, NumberRadix: 10, _maximumOutputLength: 1024, _memberDisplayFormat: SeparateLines, _numberRadix: 10 } ", s_formatter.FormatObject(options, options)); } [Fact] public void ValidEscapeNonPrintableCharacters() { var options = new PrintOptions(); options.EscapeNonPrintableCharacters = true; Assert.Equal(@"""\t""", s_formatter.FormatObject("\t", options)); Assert.Equal(@"'\t'", s_formatter.FormatObject('\t', options)); options.EscapeNonPrintableCharacters = false; Assert.Equal("\"\t\"", s_formatter.FormatObject("\t", options)); Assert.Equal("'\t'", s_formatter.FormatObject('\t', options)); } [Fact] public void ValidMaximumOutputLength() { var options = new PrintOptions(); options.MaximumOutputLength = 1; Assert.Equal("1...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 2; Assert.Equal("12...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 3; Assert.Equal("123...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 4; Assert.Equal("1234...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 5; Assert.Equal("12345...", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 6; Assert.Equal("123456", s_formatter.FormatObject(123456, options)); options.MaximumOutputLength = 7; Assert.Equal("123456", s_formatter.FormatObject(123456, options)); } [Fact] public void ValidEllipsis() { var options = new PrintOptions(); options.MaximumOutputLength = 1; options.Ellipsis = "."; Assert.Equal("1.", s_formatter.FormatObject(123456, options)); options.Ellipsis = ".."; Assert.Equal("1..", s_formatter.FormatObject(123456, options)); options.Ellipsis = ""; Assert.Equal("1", s_formatter.FormatObject(123456, options)); options.Ellipsis = null; Assert.Equal("1", s_formatter.FormatObject(123456, options)); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Binding/EarlyWellKnownAttributeBinder.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.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This is a binder for use when early decoding of well known attributes. The binder will only bind expressions that can appear in an attribute. ''' Its purpose is to allow a symbol to safely decode any attribute without the possibility of any attribute related infinite recursion during binding. ''' If an attribute and its arguments are valid then this binder returns a BoundAttributeExpression otherwise it returns a BadExpression. ''' </summary> Friend NotInheritable Class EarlyWellKnownAttributeBinder Inherits Binder Private ReadOnly _owner As Symbol Friend Sub New(owner As Symbol, containingBinder As Binder) MyBase.New(containingBinder, isEarlyAttributeBinder:=True) Me._owner = owner End Sub Public Overrides ReadOnly Property ContainingMember As Symbol Get Return If(_owner, MyBase.ContainingMember) End Get End Property Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return ImmutableArray(Of Symbol).Empty End Get End Property ' This binder is only used to bind expressions in an attribute context. Public Overrides ReadOnly Property BindingLocation As BindingLocation Get Return BindingLocation.Attribute End Get End Property ' Hide the GetAttribute overload which takes a diagnostic bag. ' This ensures that diagnostics from the early bound attributes are never preserved. Friend Shadows Function GetAttribute(node As AttributeSyntax, boundAttributeType As NamedTypeSymbol, <Out> ByRef generatedDiagnostics As Boolean) As SourceAttributeData Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, withDependencies:=False) Dim earlyAttribute = MyBase.GetAttribute(node, boundAttributeType, diagnostics) generatedDiagnostics = Not diagnostics.DiagnosticBag.IsEmptyWithoutResolution() diagnostics.Free() Return earlyAttribute End Function ''' <summary> ''' Check that the syntax can appear in an attribute argument. ''' </summary> Friend Shared Function CanBeValidAttributeArgument(node As ExpressionSyntax, memberAccessBinder As Binder) As Boolean Debug.Assert(node IsNot Nothing) ' 11.2 Constant Expressions ' 'A constant expression is an expression whose value can be fully evaluated at compile time. The type of a constant expression can be Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Char, Single, Double, Decimal, Date, Boolean, String, Object, or any enumeration type. The following constructs are permitted in constant expressions: ' ' Literals (including Nothing). ' References to constant type members or constant locals. ' References to members of enumeration types. ' Parenthesized subexpressions. ' Coercion expressions, provided the target type is one of the types listed above. Coercions to and from String are an exception to this rule and are only allowed on null values because String conversions are always done in the current culture of the execution environment at run time. Note that constant coercion expressions can only ever use intrinsic conversions. ' The +, – and Not unary operators, provided the operand and result is of a type listed above. ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, provided each operand and result is of a type listed above. ' The conditional operator If, provided each operand and result is of a type listed above. ' The following run-time functions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ' ' In addition, attributes allow array expressions including both array literal and array creation expressions as well as GetType expressions. Select Case node.Kind Case _ SyntaxKind.NumericLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NothingLiteralExpression, SyntaxKind.DateLiteralExpression ' Literals (including Nothing). Return True Case _ SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.GlobalName, SyntaxKind.IdentifierName, SyntaxKind.PredefinedType ' References to constant type members or constant locals. ' References to members of enumeration types. Return True Case SyntaxKind.ParenthesizedExpression ' Parenthesized subexpressions. Return True Case _ SyntaxKind.CTypeExpression, SyntaxKind.TryCastExpression, SyntaxKind.DirectCastExpression, SyntaxKind.PredefinedCastExpression ' Coercion expressions, provided the target type is one of the types listed above. ' Coercions to and from String are an exception to this rule and are only allowed on null values ' because String conversions are always done in the current culture of the execution environment ' at run time. Note that constant coercion expressions can only ever use intrinsic conversions. Return True Case _ SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression ' The +, – and Not unary operators, provided the operand and result is of a type listed above. Return True Case _ SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.AndExpression, SyntaxKind.OrExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.AndAlsoExpression, SyntaxKind.OrElseExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, ' provided each operand and result is of a type listed above. Return True Case _ SyntaxKind.BinaryConditionalExpression, SyntaxKind.TernaryConditionalExpression ' The conditional operator If, provided each operand and result is of a type listed above. Return True Case SyntaxKind.InvocationExpression ' The following run-time functions may appear in constant expressions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty Dim memberAccess = TryCast(DirectCast(node, InvocationExpressionSyntax).Expression, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then Dim boundExpression = memberAccessBinder.BindExpression(memberAccess, BindingDiagnosticBag.Discarded) If boundExpression.HasErrors Then Return False End If Dim boundMethodGroup = TryCast(boundExpression, BoundMethodGroup) If boundMethodGroup IsNot Nothing AndAlso boundMethodGroup.Methods.Length = 1 Then Dim method = boundMethodGroup.Methods(0) Dim compilation As VisualBasicCompilation = memberAccessBinder.Compilation If method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32) Then Return True End If End If End If Return False Case SyntaxKind.CollectionInitializer, SyntaxKind.ArrayCreationExpression, SyntaxKind.GetTypeExpression ' These are not constants and are special for attribute expressions. ' SyntaxKind.CollectionInitializer in this case really means ArrayLiteral, i.e.{1, 2, 3}. ' SyntaxKind.ArrayCreationExpression is array creation expression, i.e. new Char {'a'c, 'b'c}. ' SyntaxKind.GetTypeExpression is a GetType expression, i.e. GetType(System.String). Return True Case Else Return False End Select End Function Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions ' When early binding attributes, extension methods should always be ignored. Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.IgnoreExtensionMethods 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.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This is a binder for use when early decoding of well known attributes. The binder will only bind expressions that can appear in an attribute. ''' Its purpose is to allow a symbol to safely decode any attribute without the possibility of any attribute related infinite recursion during binding. ''' If an attribute and its arguments are valid then this binder returns a BoundAttributeExpression otherwise it returns a BadExpression. ''' </summary> Friend NotInheritable Class EarlyWellKnownAttributeBinder Inherits Binder Private ReadOnly _owner As Symbol Friend Sub New(owner As Symbol, containingBinder As Binder) MyBase.New(containingBinder, isEarlyAttributeBinder:=True) Me._owner = owner End Sub Public Overrides ReadOnly Property ContainingMember As Symbol Get Return If(_owner, MyBase.ContainingMember) End Get End Property Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return ImmutableArray(Of Symbol).Empty End Get End Property ' This binder is only used to bind expressions in an attribute context. Public Overrides ReadOnly Property BindingLocation As BindingLocation Get Return BindingLocation.Attribute End Get End Property ' Hide the GetAttribute overload which takes a diagnostic bag. ' This ensures that diagnostics from the early bound attributes are never preserved. Friend Shadows Function GetAttribute(node As AttributeSyntax, boundAttributeType As NamedTypeSymbol, <Out> ByRef generatedDiagnostics As Boolean) As SourceAttributeData Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, withDependencies:=False) Dim earlyAttribute = MyBase.GetAttribute(node, boundAttributeType, diagnostics) generatedDiagnostics = Not diagnostics.DiagnosticBag.IsEmptyWithoutResolution() diagnostics.Free() Return earlyAttribute End Function ''' <summary> ''' Check that the syntax can appear in an attribute argument. ''' </summary> Friend Shared Function CanBeValidAttributeArgument(node As ExpressionSyntax, memberAccessBinder As Binder) As Boolean Debug.Assert(node IsNot Nothing) ' 11.2 Constant Expressions ' 'A constant expression is an expression whose value can be fully evaluated at compile time. The type of a constant expression can be Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Char, Single, Double, Decimal, Date, Boolean, String, Object, or any enumeration type. The following constructs are permitted in constant expressions: ' ' Literals (including Nothing). ' References to constant type members or constant locals. ' References to members of enumeration types. ' Parenthesized subexpressions. ' Coercion expressions, provided the target type is one of the types listed above. Coercions to and from String are an exception to this rule and are only allowed on null values because String conversions are always done in the current culture of the execution environment at run time. Note that constant coercion expressions can only ever use intrinsic conversions. ' The +, – and Not unary operators, provided the operand and result is of a type listed above. ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, provided each operand and result is of a type listed above. ' The conditional operator If, provided each operand and result is of a type listed above. ' The following run-time functions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ' ' In addition, attributes allow array expressions including both array literal and array creation expressions as well as GetType expressions. Select Case node.Kind Case _ SyntaxKind.NumericLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NothingLiteralExpression, SyntaxKind.DateLiteralExpression ' Literals (including Nothing). Return True Case _ SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.GlobalName, SyntaxKind.IdentifierName, SyntaxKind.PredefinedType ' References to constant type members or constant locals. ' References to members of enumeration types. Return True Case SyntaxKind.ParenthesizedExpression ' Parenthesized subexpressions. Return True Case _ SyntaxKind.CTypeExpression, SyntaxKind.TryCastExpression, SyntaxKind.DirectCastExpression, SyntaxKind.PredefinedCastExpression ' Coercion expressions, provided the target type is one of the types listed above. ' Coercions to and from String are an exception to this rule and are only allowed on null values ' because String conversions are always done in the current culture of the execution environment ' at run time. Note that constant coercion expressions can only ever use intrinsic conversions. Return True Case _ SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression ' The +, – and Not unary operators, provided the operand and result is of a type listed above. Return True Case _ SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.AndExpression, SyntaxKind.OrExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.AndAlsoExpression, SyntaxKind.OrElseExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, ' provided each operand and result is of a type listed above. Return True Case _ SyntaxKind.BinaryConditionalExpression, SyntaxKind.TernaryConditionalExpression ' The conditional operator If, provided each operand and result is of a type listed above. Return True Case SyntaxKind.InvocationExpression ' The following run-time functions may appear in constant expressions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty Dim memberAccess = TryCast(DirectCast(node, InvocationExpressionSyntax).Expression, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then Dim boundExpression = memberAccessBinder.BindExpression(memberAccess, BindingDiagnosticBag.Discarded) If boundExpression.HasErrors Then Return False End If Dim boundMethodGroup = TryCast(boundExpression, BoundMethodGroup) If boundMethodGroup IsNot Nothing AndAlso boundMethodGroup.Methods.Length = 1 Then Dim method = boundMethodGroup.Methods(0) Dim compilation As VisualBasicCompilation = memberAccessBinder.Compilation If method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32) Then Return True End If End If End If Return False Case SyntaxKind.CollectionInitializer, SyntaxKind.ArrayCreationExpression, SyntaxKind.GetTypeExpression ' These are not constants and are special for attribute expressions. ' SyntaxKind.CollectionInitializer in this case really means ArrayLiteral, i.e.{1, 2, 3}. ' SyntaxKind.ArrayCreationExpression is array creation expression, i.e. new Char {'a'c, 'b'c}. ' SyntaxKind.GetTypeExpression is a GetType expression, i.e. GetType(System.String). Return True Case Else Return False End Select End Function Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions ' When early binding attributes, extension methods should always be ignored. Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.IgnoreExtensionMethods End Function End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingChecksumWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingChecksumWrapper { private Checksum UnderlyingObject { get; } public UnitTestingChecksumWrapper(Checksum underlyingObject) => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); public bool IsEqualTo(UnitTestingChecksumWrapper other) => other.UnderlyingObject == UnderlyingObject; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingChecksumWrapper { private Checksum UnderlyingObject { get; } public UnitTestingChecksumWrapper(Checksum underlyingObject) => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); public bool IsEqualTo(UnitTestingChecksumWrapper other) => other.UnderlyingObject == UnderlyingObject; } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/MSBuildTest/Resources/NetCoreApp2AndLibrary/Library.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0</TargetFrameworks> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0</TargetFrameworks> </PropertyGroup> </Project>
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/CodeAnalysisTest/Resources/nativeWithStringIDsAndTypesAndIntTypes.res
T 0 T4VS_VERSION_INFO ?StringFileInfo040904b0$CompanyName *FileDescriptionJFileVersion11.0.50911.0 built $InternalName (LegalCopyright ,OriginalFilename $ProductName > ProductVersion11.0.50911.0DVarFileInfo$Translation TIMAGEBACKGROUND_GRADIENT.JPG0 JFIFddDuckyP d       W Qa ?%x sZ jTwz6X@ V3tMP@u%mD25TFpɽA BPqD(ntH@h?$8IMAGEINFO.PNG0 PNG  IHDR szz pHYs+-tEXt _IDATx헯@G ^,. U x^Ă$ wo ׿,v}UMdf/=ɉv].mPVjj'BV!X7q\_EH|kU27DFvۙz}k>տT*!VL\Fp$}r. A?̑t:䷀fct: q3v$&㳷3 *rk"RKཹL&f\uvŒ8 <y4V˶Y,W< Xe9}K`NT#{p܈ 0$m `/A079r.r%g7h\Ff!-v{0RKx\3|_+4|4 8 <V倀XY XfbC2g.Ŭ@J̃Goɚ/LvA*qH<* >8C~e5iJҨGW.-XBB 改i#I93nRR;!nQ\>\rw68ۊ5pSr "Oa^a_\ PO&YG+soit+N'b4᥷yj)?<Ak+IIENDB`
T 0 T4VS_VERSION_INFO ?StringFileInfo040904b0$CompanyName *FileDescriptionJFileVersion11.0.50911.0 built $InternalName (LegalCopyright ,OriginalFilename $ProductName > ProductVersion11.0.50911.0DVarFileInfo$Translation TIMAGEBACKGROUND_GRADIENT.JPG0 JFIFddDuckyP d       W Qa ?%x sZ jTwz6X@ V3tMP@u%mD25TFpɽA BPqD(ntH@h?$8IMAGEINFO.PNG0 PNG  IHDR szz pHYs+-tEXt _IDATx헯@G ^,. U x^Ă$ wo ׿,v}UMdf/=ɉv].mPVjj'BV!X7q\_EH|kU27DFvۙz}k>տT*!VL\Fp$}r. A?̑t:䷀fct: q3v$&㳷3 *rk"RKཹL&f\uvŒ8 <y4V˶Y,W< Xe9}K`NT#{p܈ 0$m `/A079r.r%g7h\Ff!-v{0RKx\3|_+4|4 8 <V倀XY XfbC2g.Ŭ@J̃Goɚ/LvA*qH<* >8C~e5iJҨGW.-XBB 改i#I93nRR;!nQ\>\rw68ۊ5pSr "Oa^a_\ PO&YG+soit+N'b4᥷yj)?<Ak+IIENDB`
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Grammar/GrammarGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable // We only support grammar generation in the command line version for now which is the netcoreapp target #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; namespace CSharpSyntaxGenerator.Grammar { internal static class GrammarGenerator { public static string Run(List<TreeType> types) { // Syntax.xml refers to a special pseudo-element 'Modifier'. Synthesize that for the grammar. var modifiers = GetMembers<DeclarationModifiers>() .Select(m => m + "Keyword").Where(n => GetSyntaxKind(n) != SyntaxKind.None) .Select(n => new Kind { Name = n }).ToList(); types.Add(new Node { Name = "Modifier", Children = { new Field { Type = "SyntaxToken", Kinds = modifiers } } }); var rules = types.ToDictionary(n => n.Name, _ => new List<Production>()); foreach (var type in types) { if (type.Base != null && rules.TryGetValue(type.Base, out var productions)) productions.Add(RuleReference(type.Name)); if (type is Node && type.Children.Count > 0) { // Convert rules like `a: (x | y) ...` into: // a: x ... // | y ...; if (type.Children[0] is Field field && field.Kinds.Count > 0) { foreach (var kind in field.Kinds) { field.Kinds = new List<Kind> { kind }; rules[type.Name].Add(HandleChildren(type.Children)); } } else { rules[type.Name].Add(HandleChildren(type.Children)); } } } // The grammar will bottom out with certain lexical productions. Create rules for these. var lexicalRules = rules.Values.SelectMany(ps => ps).SelectMany(p => p.ReferencedRules) .Where(r => !rules.TryGetValue(r, out var productions) || productions.Count == 0).ToArray(); foreach (var name in lexicalRules) rules[name] = new List<Production> { new Production("/* see lexical specification */") }; var seen = new HashSet<string>(); // Define a few major sections to help keep the grammar file naturally grouped. var majorRules = ImmutableArray.Create( "CompilationUnitSyntax", "MemberDeclarationSyntax", "TypeSyntax", "StatementSyntax", "ExpressionSyntax", "XmlNodeSyntax", "StructuredTriviaSyntax"); var result = "// <auto-generated />" + Environment.NewLine + "grammar csharp;" + Environment.NewLine; // Handle each major section first and then walk any rules not hit transitively from them. foreach (var rule in majorRules.Concat(rules.Keys.OrderBy(a => a))) processRule(rule, ref result); return result; void processRule(string name, ref string result) { if (name != "CSharpSyntaxNode" && seen.Add(name)) { // Order the productions to keep us independent from whatever changes happen in Syntax.xml. var sorted = rules[name].OrderBy(v => v); result += Environment.NewLine + RuleReference(name).Text + Environment.NewLine + " : " + string.Join(Environment.NewLine + " | ", sorted) + Environment.NewLine + " ;" + Environment.NewLine; // Now proceed in depth-first fashion through the referenced rules to keep related rules // close by. Don't recurse into major-sections to help keep them separated in grammar file. foreach (var production in sorted) foreach (var referencedRule in production.ReferencedRules) if (!majorRules.Concat(lexicalRules).Contains(referencedRule)) processRule(referencedRule, ref result); } } } private static Production Join(string delim, IEnumerable<Production> productions) => new Production(string.Join(delim, productions.Where(p => p.Text.Length > 0)), productions.SelectMany(p => p.ReferencedRules)); private static Production HandleChildren(IEnumerable<TreeTypeChild> children, string delim = " ") => Join(delim, children.Select(child => child is Choice c ? HandleChildren(c.Children, delim: " | ").Parenthesize().Suffix("?", when: c.Optional) : child is Sequence s ? HandleChildren(s.Children).Parenthesize() : child is Field f ? HandleField(f).Suffix("?", when: f.IsOptional) : throw new InvalidOperationException())); private static Production HandleField(Field field) // 'bool' fields are for a few properties we generate on DirectiveTrivia. They're not // relevant to the grammar, so we just return an empty production to ignore them. => field.Type == "bool" ? new Production("") : field.Type == "CSharpSyntaxNode" ? RuleReference(field.Kinds.Single().Name + "Syntax") : field.Type.StartsWith("SeparatedSyntaxList") ? HandleSeparatedList(field, field.Type[("SeparatedSyntaxList".Length + 1)..^1]) : field.Type.StartsWith("SyntaxList") ? HandleList(field, field.Type[("SyntaxList".Length + 1)..^1]) : field.IsToken ? HandleTokenField(field) : RuleReference(field.Type); private static Production HandleSeparatedList(Field field, string elementType) => RuleReference(elementType).Suffix(" (',' " + RuleReference(elementType) + ")") .Suffix("*", when: field.MinCount < 2).Suffix("+", when: field.MinCount >= 2) .Suffix(" ','?", when: field.AllowTrailingSeparator) .Parenthesize(when: field.MinCount == 0).Suffix("?", when: field.MinCount == 0); private static Production HandleList(Field field, string elementType) => (elementType != "SyntaxToken" ? RuleReference(elementType) : field.Name == "Commas" ? new Production("','") : field.Name == "Modifiers" ? RuleReference("Modifier") : field.Name == "TextTokens" ? RuleReference(nameof(SyntaxKind.XmlTextLiteralToken)) : RuleReference(elementType)) .Suffix(field.MinCount == 0 ? "*" : "+"); private static Production HandleTokenField(Field field) => field.Kinds.Count == 0 ? HandleTokenName(field.Name) : Join(" | ", field.Kinds.Select(k => HandleTokenName(k.Name))).Parenthesize(when: field.Kinds.Count >= 2); private static Production HandleTokenName(string tokenName) => GetSyntaxKind(tokenName) is var kind && kind == SyntaxKind.None ? RuleReference("SyntaxToken") : SyntaxFacts.GetText(kind) is var text && text != "" ? new Production(text == "'" ? "'\\''" : $"'{text}'") : tokenName.StartsWith("EndOf") ? new Production("") : tokenName.StartsWith("Omitted") ? new Production("/* epsilon */") : RuleReference(tokenName); private static SyntaxKind GetSyntaxKind(string name) => GetMembers<SyntaxKind>().Where(k => k.ToString() == name).SingleOrDefault(); private static IEnumerable<TEnum> GetMembers<TEnum>() where TEnum : struct, Enum => (IEnumerable<TEnum>)Enum.GetValues(typeof(TEnum)); private static Production RuleReference(string name) => new Production( s_normalizationRegex.Replace(name.EndsWith("Syntax") ? name[..^"Syntax".Length] : name, "_").ToLower(), ImmutableArray.Create(name)); // Converts a PascalCased name into snake_cased name. private static readonly Regex s_normalizationRegex = new Regex( "(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); } internal struct Production : IComparable<Production> { public readonly string Text; public readonly ImmutableArray<string> ReferencedRules; public Production(string text, IEnumerable<string> referencedRules = null) { Text = text; ReferencedRules = referencedRules?.ToImmutableArray() ?? ImmutableArray<string>.Empty; } public override string ToString() => Text; public int CompareTo(Production other) => StringComparer.Ordinal.Compare(this.Text, other.Text); public Production Prefix(string prefix) => new Production(prefix + this, ReferencedRules); public Production Suffix(string suffix, bool when = true) => when ? new Production(this + suffix, ReferencedRules) : this; public Production Parenthesize(bool when = true) => when ? Prefix("(").Suffix(")") : this; } } namespace Microsoft.CodeAnalysis { internal static class GreenNode { internal const int ListKind = 1; // See SyntaxKind. } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable // We only support grammar generation in the command line version for now which is the netcoreapp target #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; namespace CSharpSyntaxGenerator.Grammar { internal static class GrammarGenerator { public static string Run(List<TreeType> types) { // Syntax.xml refers to a special pseudo-element 'Modifier'. Synthesize that for the grammar. var modifiers = GetMembers<DeclarationModifiers>() .Select(m => m + "Keyword").Where(n => GetSyntaxKind(n) != SyntaxKind.None) .Select(n => new Kind { Name = n }).ToList(); types.Add(new Node { Name = "Modifier", Children = { new Field { Type = "SyntaxToken", Kinds = modifiers } } }); var rules = types.ToDictionary(n => n.Name, _ => new List<Production>()); foreach (var type in types) { if (type.Base != null && rules.TryGetValue(type.Base, out var productions)) productions.Add(RuleReference(type.Name)); if (type is Node && type.Children.Count > 0) { // Convert rules like `a: (x | y) ...` into: // a: x ... // | y ...; if (type.Children[0] is Field field && field.Kinds.Count > 0) { foreach (var kind in field.Kinds) { field.Kinds = new List<Kind> { kind }; rules[type.Name].Add(HandleChildren(type.Children)); } } else { rules[type.Name].Add(HandleChildren(type.Children)); } } } // The grammar will bottom out with certain lexical productions. Create rules for these. var lexicalRules = rules.Values.SelectMany(ps => ps).SelectMany(p => p.ReferencedRules) .Where(r => !rules.TryGetValue(r, out var productions) || productions.Count == 0).ToArray(); foreach (var name in lexicalRules) rules[name] = new List<Production> { new Production("/* see lexical specification */") }; var seen = new HashSet<string>(); // Define a few major sections to help keep the grammar file naturally grouped. var majorRules = ImmutableArray.Create( "CompilationUnitSyntax", "MemberDeclarationSyntax", "TypeSyntax", "StatementSyntax", "ExpressionSyntax", "XmlNodeSyntax", "StructuredTriviaSyntax"); var result = "// <auto-generated />" + Environment.NewLine + "grammar csharp;" + Environment.NewLine; // Handle each major section first and then walk any rules not hit transitively from them. foreach (var rule in majorRules.Concat(rules.Keys.OrderBy(a => a))) processRule(rule, ref result); return result; void processRule(string name, ref string result) { if (name != "CSharpSyntaxNode" && seen.Add(name)) { // Order the productions to keep us independent from whatever changes happen in Syntax.xml. var sorted = rules[name].OrderBy(v => v); result += Environment.NewLine + RuleReference(name).Text + Environment.NewLine + " : " + string.Join(Environment.NewLine + " | ", sorted) + Environment.NewLine + " ;" + Environment.NewLine; // Now proceed in depth-first fashion through the referenced rules to keep related rules // close by. Don't recurse into major-sections to help keep them separated in grammar file. foreach (var production in sorted) foreach (var referencedRule in production.ReferencedRules) if (!majorRules.Concat(lexicalRules).Contains(referencedRule)) processRule(referencedRule, ref result); } } } private static Production Join(string delim, IEnumerable<Production> productions) => new Production(string.Join(delim, productions.Where(p => p.Text.Length > 0)), productions.SelectMany(p => p.ReferencedRules)); private static Production HandleChildren(IEnumerable<TreeTypeChild> children, string delim = " ") => Join(delim, children.Select(child => child is Choice c ? HandleChildren(c.Children, delim: " | ").Parenthesize().Suffix("?", when: c.Optional) : child is Sequence s ? HandleChildren(s.Children).Parenthesize() : child is Field f ? HandleField(f).Suffix("?", when: f.IsOptional) : throw new InvalidOperationException())); private static Production HandleField(Field field) // 'bool' fields are for a few properties we generate on DirectiveTrivia. They're not // relevant to the grammar, so we just return an empty production to ignore them. => field.Type == "bool" ? new Production("") : field.Type == "CSharpSyntaxNode" ? RuleReference(field.Kinds.Single().Name + "Syntax") : field.Type.StartsWith("SeparatedSyntaxList") ? HandleSeparatedList(field, field.Type[("SeparatedSyntaxList".Length + 1)..^1]) : field.Type.StartsWith("SyntaxList") ? HandleList(field, field.Type[("SyntaxList".Length + 1)..^1]) : field.IsToken ? HandleTokenField(field) : RuleReference(field.Type); private static Production HandleSeparatedList(Field field, string elementType) => RuleReference(elementType).Suffix(" (',' " + RuleReference(elementType) + ")") .Suffix("*", when: field.MinCount < 2).Suffix("+", when: field.MinCount >= 2) .Suffix(" ','?", when: field.AllowTrailingSeparator) .Parenthesize(when: field.MinCount == 0).Suffix("?", when: field.MinCount == 0); private static Production HandleList(Field field, string elementType) => (elementType != "SyntaxToken" ? RuleReference(elementType) : field.Name == "Commas" ? new Production("','") : field.Name == "Modifiers" ? RuleReference("Modifier") : field.Name == "TextTokens" ? RuleReference(nameof(SyntaxKind.XmlTextLiteralToken)) : RuleReference(elementType)) .Suffix(field.MinCount == 0 ? "*" : "+"); private static Production HandleTokenField(Field field) => field.Kinds.Count == 0 ? HandleTokenName(field.Name) : Join(" | ", field.Kinds.Select(k => HandleTokenName(k.Name))).Parenthesize(when: field.Kinds.Count >= 2); private static Production HandleTokenName(string tokenName) => GetSyntaxKind(tokenName) is var kind && kind == SyntaxKind.None ? RuleReference("SyntaxToken") : SyntaxFacts.GetText(kind) is var text && text != "" ? new Production(text == "'" ? "'\\''" : $"'{text}'") : tokenName.StartsWith("EndOf") ? new Production("") : tokenName.StartsWith("Omitted") ? new Production("/* epsilon */") : RuleReference(tokenName); private static SyntaxKind GetSyntaxKind(string name) => GetMembers<SyntaxKind>().Where(k => k.ToString() == name).SingleOrDefault(); private static IEnumerable<TEnum> GetMembers<TEnum>() where TEnum : struct, Enum => (IEnumerable<TEnum>)Enum.GetValues(typeof(TEnum)); private static Production RuleReference(string name) => new Production( s_normalizationRegex.Replace(name.EndsWith("Syntax") ? name[..^"Syntax".Length] : name, "_").ToLower(), ImmutableArray.Create(name)); // Converts a PascalCased name into snake_cased name. private static readonly Regex s_normalizationRegex = new Regex( "(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); } internal struct Production : IComparable<Production> { public readonly string Text; public readonly ImmutableArray<string> ReferencedRules; public Production(string text, IEnumerable<string> referencedRules = null) { Text = text; ReferencedRules = referencedRules?.ToImmutableArray() ?? ImmutableArray<string>.Empty; } public override string ToString() => Text; public int CompareTo(Production other) => StringComparer.Ordinal.Compare(this.Text, other.Text); public Production Prefix(string prefix) => new Production(prefix + this, ReferencedRules); public Production Suffix(string suffix, bool when = true) => when ? new Production(this + suffix, ReferencedRules) : this; public Production Parenthesize(bool when = true) => when ? Prefix("(").Suffix(")") : this; } } namespace Microsoft.CodeAnalysis { internal static class GreenNode { internal const int ListKind = 1; // See SyntaxKind. } } #endif
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteEditAndContinueService : BrokeredServiceBase, IRemoteEditAndContinueService { internal sealed class Factory : FactoryBase<IRemoteEditAndContinueService, IRemoteEditAndContinueService.ICallback> { protected override IRemoteEditAndContinueService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) => new RemoteEditAndContinueService(arguments, callback); } private sealed class ManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService { private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public ManagedEditAndContinueDebuggerService(RemoteCallback<IRemoteEditAndContinueService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } Task<ImmutableArray<ManagedActiveStatementDebugInfo>> IManagedEditAndContinueDebuggerService.GetActiveStatementsAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetActiveStatementsAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task<ManagedEditAndContinueAvailability> IManagedEditAndContinueDebuggerService.GetAvailabilityAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetAvailabilityAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); Task<ImmutableArray<string>> IManagedEditAndContinueDebuggerService.GetCapabilitiesAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetCapabilitiesAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task IManagedEditAndContinueDebuggerService.PrepareModuleForUpdateAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.PrepareModuleForUpdateAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); } private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; public RemoteEditAndContinueService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) : base(arguments) { _callback = callback; } private IEditAndContinueWorkspaceService GetService() => GetWorkspace().Services.GetRequiredService<IEditAndContinueWorkspaceService>(); private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServiceCallbackId callbackId) => new((documentId, filePath, cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetSpansAsync(callbackId, documentId, filePath, cancellationToken), cancellationToken)); /// <summary> /// Remote API. /// </summary> public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId); var sessionId = await GetService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false); return sessionId; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> BreakStateEnteredAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().BreakStateEntered(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().EndDebuggingSession(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var diagnostics = await GetService().GetDocumentDiagnosticsAsync(document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return diagnostics.SelectAsArray(diagnostic => DiagnosticData.Create(diagnostic, document)); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().HasChangesAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), sourceFilePath, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var service = GetService(); var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); try { var results = await service.EmitSolutionUpdateAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return results.Dehydrate(solution); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError); var diagnostic = Diagnostic.Create(descriptor, Location.None, new[] { e.Message }); var diagnostics = ImmutableArray.Create(DiagnosticData.Create(diagnostic, solution.Options)); return new EmitSolutionUpdateResults.Data(updates, diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty); } }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().CommitSolutionUpdate(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().DiscardSolutionUpdate(sessionId); return default; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetBaseActiveStatementSpansAsync(sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); return await GetService().GetAdjustedActiveStatementSpansAsync(sessionId, document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().IsActiveStatementInExceptionRegionAsync(sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetCurrentActiveStatementPositionAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); // TODO: Non-C#/VB documents are not currently serialized to remote workspace. // https://github.com/dotnet/roslyn/issues/47341 var document = solution.GetDocument(documentId); if (document != null) { GetService().OnSourceFileUpdated(document); } }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteEditAndContinueService : BrokeredServiceBase, IRemoteEditAndContinueService { internal sealed class Factory : FactoryBase<IRemoteEditAndContinueService, IRemoteEditAndContinueService.ICallback> { protected override IRemoteEditAndContinueService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) => new RemoteEditAndContinueService(arguments, callback); } private sealed class ManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService { private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public ManagedEditAndContinueDebuggerService(RemoteCallback<IRemoteEditAndContinueService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } Task<ImmutableArray<ManagedActiveStatementDebugInfo>> IManagedEditAndContinueDebuggerService.GetActiveStatementsAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetActiveStatementsAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task<ManagedEditAndContinueAvailability> IManagedEditAndContinueDebuggerService.GetAvailabilityAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetAvailabilityAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); Task<ImmutableArray<string>> IManagedEditAndContinueDebuggerService.GetCapabilitiesAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetCapabilitiesAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task IManagedEditAndContinueDebuggerService.PrepareModuleForUpdateAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.PrepareModuleForUpdateAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); } private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; public RemoteEditAndContinueService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) : base(arguments) { _callback = callback; } private IEditAndContinueWorkspaceService GetService() => GetWorkspace().Services.GetRequiredService<IEditAndContinueWorkspaceService>(); private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServiceCallbackId callbackId) => new((documentId, filePath, cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetSpansAsync(callbackId, documentId, filePath, cancellationToken), cancellationToken)); /// <summary> /// Remote API. /// </summary> public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId); var sessionId = await GetService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false); return sessionId; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> BreakStateEnteredAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().BreakStateEntered(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().EndDebuggingSession(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var diagnostics = await GetService().GetDocumentDiagnosticsAsync(document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return diagnostics.SelectAsArray(diagnostic => DiagnosticData.Create(diagnostic, document)); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().HasChangesAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), sourceFilePath, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var service = GetService(); var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); try { var results = await service.EmitSolutionUpdateAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return results.Dehydrate(solution); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError); var diagnostic = Diagnostic.Create(descriptor, Location.None, new[] { e.Message }); var diagnostics = ImmutableArray.Create(DiagnosticData.Create(diagnostic, solution.Options)); return new EmitSolutionUpdateResults.Data(updates, diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty); } }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().CommitSolutionUpdate(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().DiscardSolutionUpdate(sessionId); return default; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetBaseActiveStatementSpansAsync(sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); return await GetService().GetAdjustedActiveStatementSpansAsync(sessionId, document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().IsActiveStatementInExceptionRegionAsync(sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetCurrentActiveStatementPositionAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); // TODO: Non-C#/VB documents are not currently serialized to remote workspace. // https://github.com/dotnet/roslyn/issues/47341 var document = solution.GetDocument(documentId); if (document != null) { GetService().OnSourceFileUpdated(document); } }, cancellationToken); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Interactive/Host/xlf/InteractiveHostResources.cs.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="cs" original="../InteractiveHostResources.resx"> <body> <trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying"> <source>Attempt to connect to process #{0} failed, retrying ...</source> <target state="translated">Pokus o připojení k procesu #{0} se nepovedl. Akce se opakuje...</target> <note /> </trans-unit> <trans-unit id="Cannot_resolve_reference_0"> <source>Cannot resolve reference '{0}'.</source> <target state="translated">Nejde vyřešit odkaz {0}.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution"> <source>Failed to create a remote process for interactive code execution: '{0}'</source> <target state="translated">Nepovedlo se vytvořit vzdálený proces pro provádění interaktivního kódu: {0}</target> <note /> </trans-unit> <trans-unit id="Failed_to_initialize_remote_interactive_process"> <source>Failed to initialize remote interactive process.</source> <target state="translated">Nepodařilo se inicializovat vzdálený interaktivní proces.</target> <note /> </trans-unit> <trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon"> <source>Failed to launch '{0}' process (exit code: {1}) with output: </source> <target state="translated">Nepodařilo se spustit proces {0} (ukončovací kód: {1}) s výstupem: </target> <note /> </trans-unit> <trans-unit id="Hosting_process_exited_with_exit_code_0"> <source>Hosting process exited with exit code {0}.</source> <target state="translated">Hostovací proces skončil s ukončovacím kódem {0}.</target> <note /> </trans-unit> <trans-unit id="Interactive_Host_not_initialized"> <source>Interactive Host not initialized.</source> <target state="translated">Interaktivní hostitel není inicializovaný.</target> <note /> </trans-unit> <trans-unit id="Loading_context_from_0"> <source>Loading context from '{0}'.</source> <target state="translated">Načítá se kontext z {0}.</target> <note /> </trans-unit> <trans-unit id="Searched_in_directories_colon"> <source>Searched in directories:</source> <target state="translated">Prohledané adresáře:</target> <note /> </trans-unit> <trans-unit id="Searched_in_directory_colon"> <source>Searched in directory:</source> <target state="translated">Prohledaný adresář:</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found"> <source>Specified file not found.</source> <target state="translated">Zadaný soubor se nenašel.</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found_colon_0"> <source>Specified file not found: {0}</source> <target state="translated">Nenalezený určený soubor: {0}</target> <note /> </trans-unit> <trans-unit id="Type_Sharphelp_for_more_information"> <source>Type "#help" for more information.</source> <target state="translated">Zadáním #help si zobrazíte víc informací.</target> <note /> </trans-unit> <trans-unit id="Unable_to_create_hosting_process"> <source>Unable to create hosting process.</source> <target state="translated">Nelze vytvořit hostovací proces.</target> <note /> </trans-unit> <trans-unit id="plus_additional_0_1"> <source> + additional {0} {1}</source> <target state="translated"> + dalších {0} {1}</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="cs" original="../InteractiveHostResources.resx"> <body> <trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying"> <source>Attempt to connect to process #{0} failed, retrying ...</source> <target state="translated">Pokus o připojení k procesu #{0} se nepovedl. Akce se opakuje...</target> <note /> </trans-unit> <trans-unit id="Cannot_resolve_reference_0"> <source>Cannot resolve reference '{0}'.</source> <target state="translated">Nejde vyřešit odkaz {0}.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution"> <source>Failed to create a remote process for interactive code execution: '{0}'</source> <target state="translated">Nepovedlo se vytvořit vzdálený proces pro provádění interaktivního kódu: {0}</target> <note /> </trans-unit> <trans-unit id="Failed_to_initialize_remote_interactive_process"> <source>Failed to initialize remote interactive process.</source> <target state="translated">Nepodařilo se inicializovat vzdálený interaktivní proces.</target> <note /> </trans-unit> <trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon"> <source>Failed to launch '{0}' process (exit code: {1}) with output: </source> <target state="translated">Nepodařilo se spustit proces {0} (ukončovací kód: {1}) s výstupem: </target> <note /> </trans-unit> <trans-unit id="Hosting_process_exited_with_exit_code_0"> <source>Hosting process exited with exit code {0}.</source> <target state="translated">Hostovací proces skončil s ukončovacím kódem {0}.</target> <note /> </trans-unit> <trans-unit id="Interactive_Host_not_initialized"> <source>Interactive Host not initialized.</source> <target state="translated">Interaktivní hostitel není inicializovaný.</target> <note /> </trans-unit> <trans-unit id="Loading_context_from_0"> <source>Loading context from '{0}'.</source> <target state="translated">Načítá se kontext z {0}.</target> <note /> </trans-unit> <trans-unit id="Searched_in_directories_colon"> <source>Searched in directories:</source> <target state="translated">Prohledané adresáře:</target> <note /> </trans-unit> <trans-unit id="Searched_in_directory_colon"> <source>Searched in directory:</source> <target state="translated">Prohledaný adresář:</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found"> <source>Specified file not found.</source> <target state="translated">Zadaný soubor se nenašel.</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found_colon_0"> <source>Specified file not found: {0}</source> <target state="translated">Nenalezený určený soubor: {0}</target> <note /> </trans-unit> <trans-unit id="Type_Sharphelp_for_more_information"> <source>Type "#help" for more information.</source> <target state="translated">Zadáním #help si zobrazíte víc informací.</target> <note /> </trans-unit> <trans-unit id="Unable_to_create_hosting_process"> <source>Unable to create hosting process.</source> <target state="translated">Nelze vytvořit hostovací proces.</target> <note /> </trans-unit> <trans-unit id="plus_additional_0_1"> <source> + additional {0} {1}</source> <target state="translated"> + dalších {0} {1}</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/FieldReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class FieldReferenceFinder : AbstractCallFinder { public FieldReferenceFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { } public override string DisplayName { get { return string.Format(EditorFeaturesResources.References_To_Field_0, SymbolName); } } protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var callers = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return callers.Where(c => c.IsDirect); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class FieldReferenceFinder : AbstractCallFinder { public FieldReferenceFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { } public override string DisplayName { get { return string.Format(EditorFeaturesResources.References_To_Field_0, SymbolName); } } protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var callers = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return callers.Where(c => c.IsDirect); } } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { using static EmbeddedSyntaxHelpers; using static RegexHelpers; using RegexNodeOrToken = EmbeddedSyntaxNodeOrToken<RegexKind, RegexNode>; using RegexToken = EmbeddedSyntaxToken<RegexKind>; using RegexTrivia = EmbeddedSyntaxTrivia<RegexKind>; /// <summary> /// Produces a <see cref="RegexTree"/> from a sequence of <see cref="VirtualChar"/> characters. /// /// Importantly, this parser attempts to replicate diagnostics with almost the exact same text /// as the native .NET regex parser. This is important so that users get an understandable /// experience where it appears to them that this is all one cohesive system and that the IDE /// will let them discover and fix the same issues they would encounter when previously trying /// to just compile and execute these regexes. /// </summary> /// <remarks> /// Invariants we try to maintain (and should consider a bug if we do not): l 1. If the .NET /// regex parser does not report an error for a given pattern, we should not either. it would be /// very bad if we told the user there was something wrong with there pattern when there really /// wasn't. /// /// 2. If the .NET regex parser does report an error for a given pattern, we should either not /// report an error (not recommended) or report the same error at an appropriate location in the /// pattern. Not reporting the error can be confusing as the user will think their pattern is /// ok, when it really is not. However, it can be acceptable to do this as it's not telling /// them that something is actually wrong, and it may be too difficult to find and report the /// same error. Note: there is only one time we do this in this parser (see the deviation /// documented in <see cref="ParsePossibleEcmascriptBackreferenceEscape"/>). /// /// Note1: "report the same error" means that we will attempt to report the error using the same /// text the .NET regex parser uses for its error messages. This is so that the user is not /// confused when they use the IDE vs running the regex by getting different messages for the /// same issue. /// /// Note2: the above invariants make life difficult at times. This happens due to the fact that /// the .NET parser is multi-pass. Meaning it does a first scan (which may report errors), then /// does the full parse. This means that it might report an error in a later location during /// the initial scan than it would during the parse. We replicate that behavior to follow the /// second invariant. /// /// Note3: It would be nice if we could check these invariants at runtime, so we could control /// our behavior by the behavior of the real .NET regex engine. For example, if the .NET regex /// engine did not report any issues, we could suppress any diagnostics we generated and we /// could log an NFW to record which pattern we deviated on so we could fix the issue for a /// future release. However, we cannot do this as the .NET regex engine has no guarantees about /// its performance characteristics. For example, certain regex patterns might end up causing /// that engine to consume unbounded amounts of CPU and memory. This is because the .NET regex /// engine is not just a parser, but something that builds an actual recognizer using techniques /// that are not necessarily bounded. As such, while we test ourselves around it during our /// tests, we cannot do the same at runtime as part of the IDE. /// /// This parser was based off the corefx RegexParser based at: /// https://github.com/dotnet/corefx/blob/f759243d724f462da0bcef54e86588f8a55352c6/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs#L1 /// /// Note4: The .NET parser itself changes over time (for example to fix behavior that even it /// thinks is buggy). When this happens, we have to make a choice as to which behavior to /// follow. In general, the overall principle is that we should follow the more lenient /// behavior. If we end up taking the more strict interpretation we risk giving people an error /// during design time that they would not get at runtime. It's far worse to have that than to /// not report an error, even though one might happen later. /// </remarks> internal partial struct RegexParser { private readonly ImmutableDictionary<string, TextSpan> _captureNamesToSpan; private readonly ImmutableDictionary<int, TextSpan> _captureNumbersToSpan; private RegexLexer _lexer; private RegexOptions _options; private RegexToken _currentToken; private int _recursionDepth; private RegexParser( VirtualCharSequence text, RegexOptions options, ImmutableDictionary<string, TextSpan> captureNamesToSpan, ImmutableDictionary<int, TextSpan> captureNumbersToSpan) : this() { _lexer = new RegexLexer(text); _options = options; _captureNamesToSpan = captureNamesToSpan; _captureNumbersToSpan = captureNumbersToSpan; // Get the first token. It is allowed to have trivia on it. ConsumeCurrentToken(allowTrivia: true); } /// <summary> /// Returns the latest token the lexer has produced, and then asks the lexer to /// produce the next token after that. /// </summary> /// <param name="allowTrivia">Whether or not trivia is allowed on the next token /// produced. In the .NET parser trivia is only allowed on a few constructs, /// and our parser mimics that behavior. Note that even if trivia is allowed, /// the type of trivia that can be scanned depends on the current RegexOptions. /// For example, if <see cref="RegexOptions.IgnorePatternWhitespace"/> is currently /// enabled, then '#...' comments are allowed. Otherwise, only '(?#...)' comments /// are allowed.</param> private RegexToken ConsumeCurrentToken(bool allowTrivia) { var previous = _currentToken; _currentToken = _lexer.ScanNextToken(allowTrivia, _options); return previous; } /// <summary> /// Given an input text, and set of options, parses out a fully representative syntax tree /// and list of diagnostics. Parsing should always succeed, except in the case of the stack /// overflowing. /// </summary> public static RegexTree TryParse(VirtualCharSequence text, RegexOptions options) { if (text.IsDefault) { return null; } try { // Parse the tree once, to figure out the capture groups. These are needed // to then parse the tree again, as the captures will affect how we interpret // certain things (i.e. escape references) and what errors will be reported. // // This is necessary as .NET regexes allow references to *future* captures. // As such, we don't know when we're seeing a reference if it's to something // that exists or not. var tree1 = new RegexParser(text, options, ImmutableDictionary<string, TextSpan>.Empty, ImmutableDictionary<int, TextSpan>.Empty).ParseTree(); var (captureNames, captureNumbers) = CaptureInfoAnalyzer.Analyze(text, tree1.Root, options); var tree2 = new RegexParser( text, options, captureNames, captureNumbers).ParseTree(); return tree2; } catch (InsufficientExecutionStackException) { return null; } } private RegexTree ParseTree() { // Most callers to ParseAlternatingSequences are from group constructs. As those // constructs will have already consumed the open paren, they don't want this sub-call // to consume through close-paren tokens as they want that token for themselves. // However, we're the topmost call and have not consumed an open paren. And, we want // this call to consume all the way to the end, eating up excess close-paren tokens that // are encountered. var expression = this.ParseAlternatingSequences(consumeCloseParen: true); Debug.Assert(_lexer.Position == _lexer.Text.Length); Debug.Assert(_currentToken.Kind == RegexKind.EndOfFile); var root = new RegexCompilationUnit(expression, _currentToken); var seenDiagnostics = new HashSet<EmbeddedDiagnostic>(); using var _ = ArrayBuilder<EmbeddedDiagnostic>.GetInstance(out var diagnostics); CollectDiagnostics(root, seenDiagnostics, diagnostics); return new RegexTree( _lexer.Text, root, diagnostics.ToImmutable(), _captureNamesToSpan, _captureNumbersToSpan); } private static void CollectDiagnostics( RegexNode node, HashSet<EmbeddedDiagnostic> seenDiagnostics, ArrayBuilder<EmbeddedDiagnostic> diagnostics) { foreach (var child in node) { if (child.IsNode) { CollectDiagnostics(child.Node, seenDiagnostics, diagnostics); } else { var token = child.Token; foreach (var trivia in token.LeadingTrivia) { AddUniqueDiagnostics(seenDiagnostics, trivia.Diagnostics, diagnostics); } // We never place trailing trivia on regex tokens. Debug.Assert(token.TrailingTrivia.IsEmpty); AddUniqueDiagnostics(seenDiagnostics, token.Diagnostics, diagnostics); } } } /// <summary> /// It's very common to have duplicated diagnostics. For example, consider "((". This will /// have two 'missing )' diagnostics, both at the end. Reporting both isn't helpful, so we /// filter duplicates out here. /// </summary> private static void AddUniqueDiagnostics( HashSet<EmbeddedDiagnostic> seenDiagnostics, ImmutableArray<EmbeddedDiagnostic> from, ArrayBuilder<EmbeddedDiagnostic> to) { foreach (var diagnostic in from) { if (seenDiagnostics.Add(diagnostic)) { to.Add(diagnostic); } } } private RegexExpressionNode ParseAlternatingSequences(bool consumeCloseParen) { try { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); return ParseAlternatingSequencesWorker(consumeCloseParen); } finally { _recursionDepth--; } } /// <summary> /// Parses out code of the form: ...|...|... /// This is the type of code you have at the top level of a regex, or inside any grouping /// contruct. Note that sequences can be empty in .NET regex. i.e. the following is legal: /// /// ...||... /// /// An empty sequence just means "match at every position in the test string". /// </summary> private RegexExpressionNode ParseAlternatingSequencesWorker(bool consumeCloseParen) { RegexExpressionNode current = ParseSequence(consumeCloseParen); while (_currentToken.Kind == RegexKind.BarToken) { // Trivia allowed between the | and the next token. current = new RegexAlternationNode( current, ConsumeCurrentToken(allowTrivia: true), ParseSequence(consumeCloseParen)); } return current; } private RegexSequenceNode ParseSequence(bool consumeCloseParen) { using var _1 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var builder); while (ShouldConsumeSequenceElement(consumeCloseParen)) { var last = builder.Count == 0 ? null : builder.Last(); builder.Add(ParsePrimaryExpressionAndQuantifiers(last)); } // We wil commonly get tons of text nodes in a row. For example, the // regex `abc` will be three text nodes in a row. To help save on memory // try to merge that into one single text node. using var _2 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var sequence); MergeTextNodes(builder, sequence); return new RegexSequenceNode(sequence.ToImmutable()); } private static void MergeTextNodes(ArrayBuilder<RegexExpressionNode> list, ArrayBuilder<RegexExpressionNode> final) { // Iterate all the nodes in the sequence we have, adding them directly to // `final` if they are not text nodes. If they are text nodes, we attempt // to keep merging them with any following text nodes as long as well. for (var index = 0; index < list.Count;) { var current = list[index]; if (current.Kind != RegexKind.Text) { // Not a text node. Just add as-is, and move to the next node. index++; final.Add(current); continue; } // Got a text node. Try to combine it with all following nodes. index = MergeAndAddAdjacentTextNodes(list, final, index); } return; // local functions static int MergeAndAddAdjacentTextNodes( ArrayBuilder<RegexExpressionNode> list, ArrayBuilder<RegexExpressionNode> final, int index) { var startIndex = index; var startTextNode = (RegexTextNode)list[startIndex]; // Keep walking forward as long as we hit text nodes and we can // merge that text node with the previous text node. index++; var lastTextNode = startTextNode; for (; index < list.Count; index++) { var currentNode = list[index]; if (!CanMerge(lastTextNode, currentNode)) { // Hit something we couldn't merge with our last text node // Break out and merge what we have so far. 'index' will // be pointing at the right node for our caller. break; } lastTextNode = (RegexTextNode)currentNode; } // If didn't have multiple text nodes in a row. Just return the // starting node. Otherwise, create one text node that has a token // that spans from the start of the first node to the end of the last node. final.Add(startTextNode == lastTextNode ? startTextNode : new RegexTextNode(CreateToken( RegexKind.TextToken, startTextNode.TextToken.LeadingTrivia, VirtualCharSequence.FromBounds( startTextNode.TextToken.VirtualChars, lastTextNode.TextToken.VirtualChars)))); return index; } // Local functions static bool CanMerge(RegexTextNode lastNode, RegexExpressionNode next) { if (next.Kind == RegexKind.Text) { var lastTextToken = lastNode.TextToken; var nextTextToken = ((RegexTextNode)next).TextToken; // Can't merge if the next text node has leading trivia. Also, conservatively // don't allow merging if there are diagnostics or values for these tokens. // We might be able to support that, but it's easier to not do anything that // might break an expectation someone might have downstream. / if (lastTextToken.Diagnostics.Length == 0 && nextTextToken.Diagnostics.Length == 0 && lastTextToken.Value == null && nextTextToken.Value == null && nextTextToken.LeadingTrivia.Length == 0) { lastTextToken.VirtualChars.AssertAdjacentTo(nextTextToken.VirtualChars); return true; } } return false; } } private bool ShouldConsumeSequenceElement(bool consumeCloseParen) { if (_currentToken.Kind == RegexKind.EndOfFile) { return false; } if (_currentToken.Kind == RegexKind.BarToken) { return false; } if (_currentToken.Kind == RegexKind.CloseParenToken) { return consumeCloseParen; } return true; } private RegexExpressionNode ParsePrimaryExpressionAndQuantifiers(RegexExpressionNode lastExpression) { var current = ParsePrimaryExpression(lastExpression); if (current.Kind == RegexKind.SimpleOptionsGrouping) { // Simple options (i.e. "(?i-x)" can't have quantifiers attached to them). return current; } return _currentToken.Kind switch { RegexKind.AsteriskToken => ParseZeroOrMoreQuantifier(current), RegexKind.PlusToken => ParseOneOrMoreQuantifier(current), RegexKind.QuestionToken => ParseZeroOrOneQuantifier(current), RegexKind.OpenBraceToken => TryParseNumericQuantifier(current, _currentToken), _ => current, }; } private RegexExpressionNode TryParseLazyQuantifier(RegexQuantifierNode quantifier) { if (_currentToken.Kind != RegexKind.QuestionToken) { return quantifier; } // Whitespace allowed after the question and the next sequence element. return new RegexLazyQuantifierNode(quantifier, ConsumeCurrentToken(allowTrivia: true)); } private RegexExpressionNode ParseZeroOrMoreQuantifier(RegexPrimaryExpressionNode current) { // Whitespace allowed between the quantifier and the possible following ? or next sequence item. return TryParseLazyQuantifier(new RegexZeroOrMoreQuantifierNode(current, ConsumeCurrentToken(allowTrivia: true))); } private RegexExpressionNode ParseOneOrMoreQuantifier(RegexPrimaryExpressionNode current) { // Whitespace allowed between the quantifier and the possible following ? or next sequence item. return TryParseLazyQuantifier(new RegexOneOrMoreQuantifierNode(current, ConsumeCurrentToken(allowTrivia: true))); } private RegexExpressionNode ParseZeroOrOneQuantifier(RegexPrimaryExpressionNode current) { // Whitespace allowed between the quantifier and the possible following ? or next sequence item. return TryParseLazyQuantifier(new RegexZeroOrOneQuantifierNode(current, ConsumeCurrentToken(allowTrivia: true))); } private RegexExpressionNode TryParseNumericQuantifier( RegexPrimaryExpressionNode expression, RegexToken openBraceToken) { var start = _lexer.Position; if (!TryParseNumericQuantifierParts( out var firstNumberToken, out var commaToken, out var secondNumberToken, out var closeBraceToken)) { _currentToken = openBraceToken; _lexer.Position = start; return expression; } var quantifier = CreateQuantifier( expression, openBraceToken, firstNumberToken, commaToken, secondNumberToken, closeBraceToken); return TryParseLazyQuantifier(quantifier); } private static RegexQuantifierNode CreateQuantifier( RegexPrimaryExpressionNode expression, RegexToken openBraceToken, RegexToken firstNumberToken, RegexToken? commaToken, RegexToken? secondNumberToken, RegexToken closeBraceToken) { if (commaToken != null) { return secondNumberToken != null ? new RegexClosedNumericRangeQuantifierNode(expression, openBraceToken, firstNumberToken, commaToken.Value, secondNumberToken.Value, closeBraceToken) : (RegexQuantifierNode)new RegexOpenNumericRangeQuantifierNode(expression, openBraceToken, firstNumberToken, commaToken.Value, closeBraceToken); } return new RegexExactNumericQuantifierNode(expression, openBraceToken, firstNumberToken, closeBraceToken); } private bool TryParseNumericQuantifierParts( out RegexToken firstNumberToken, out RegexToken? commaToken, out RegexToken? secondNumberToken, out RegexToken closeBraceToken) { firstNumberToken = default; commaToken = null; secondNumberToken = null; closeBraceToken = default; var firstNumber = _lexer.TryScanNumber(); if (firstNumber == null) { return false; } firstNumberToken = firstNumber.Value; // Nothing allowed between {x,n} ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.CommaToken) { commaToken = _currentToken; var start = _lexer.Position; secondNumberToken = _lexer.TryScanNumber(); if (secondNumberToken == null) { // Nothing allowed between {x,n} ResetToPositionAndConsumeCurrentToken(start, allowTrivia: false); } else { var secondNumberTokenLocal = secondNumberToken.Value; // Nothing allowed between {x,n} ConsumeCurrentToken(allowTrivia: false); var val1 = (int)firstNumberToken.Value; var val2 = (int)secondNumberTokenLocal.Value; if (val2 < val1) { secondNumberTokenLocal = secondNumberTokenLocal.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Illegal_x_y_with_x_less_than_y, secondNumberTokenLocal.GetSpan())); secondNumberToken = secondNumberTokenLocal; } } } if (_currentToken.Kind != RegexKind.CloseBraceToken) { return false; } // Whitespace allowed between the quantifier and the possible following ? or next sequence item. closeBraceToken = ConsumeCurrentToken(allowTrivia: true); return true; } private void ResetToPositionAndConsumeCurrentToken(int position, bool allowTrivia) { _lexer.Position = position; ConsumeCurrentToken(allowTrivia); } private RegexPrimaryExpressionNode ParsePrimaryExpression(RegexExpressionNode lastExpression) { switch (_currentToken.Kind) { case RegexKind.DotToken: return ParseWildcard(); case RegexKind.CaretToken: return ParseStartAnchor(); case RegexKind.DollarToken: return ParseEndAnchor(); case RegexKind.BackslashToken: return ParseEscape(_currentToken, allowTriviaAfterEnd: true); case RegexKind.OpenBracketToken: return ParseCharacterClass(); case RegexKind.OpenParenToken: return ParseGrouping(); case RegexKind.CloseParenToken: return ParseUnexpectedCloseParenToken(); case RegexKind.OpenBraceToken: return ParsePossibleUnexpectedNumericQuantifier(lastExpression); case RegexKind.AsteriskToken: case RegexKind.PlusToken: case RegexKind.QuestionToken: return ParseUnexpectedQuantifier(lastExpression); default: return ParseText(); } } private RegexPrimaryExpressionNode ParsePossibleUnexpectedNumericQuantifier(RegexExpressionNode lastExpression) { // Native parser looks for something like {0,1} in a top level sequence and reports // an explicit error that that's not allowed. However, something like {0, 1} is fine // and is treated as six textual tokens. var openBraceToken = _currentToken.With(kind: RegexKind.TextToken); var start = _lexer.Position; if (TryParseNumericQuantifierParts( out _, out _, out _, out _)) { // Report that a numeric quantifier isn't allowed here. CheckQuantifierExpression(lastExpression, ref openBraceToken); } // Started with { but wasn't a numeric quantifier. This is totally legal and is just // a textual sequence. Restart, scanning this token as a normal sequence element. ResetToPositionAndConsumeCurrentToken(start, allowTrivia: true); return new RegexTextNode(openBraceToken); } private RegexPrimaryExpressionNode ParseUnexpectedCloseParenToken() { var token = _currentToken.With(kind: RegexKind.TextToken).AddDiagnosticIfNone( new EmbeddedDiagnostic(FeaturesResources.Too_many_close_parens, _currentToken.GetSpan())); // Technically, since an error occurred, we can do whatever we want here. However, // the spirit of the native parser is that top level sequence elements are allowed // to have trivia. So that's the behavior we mimic. ConsumeCurrentToken(allowTrivia: true); return new RegexTextNode(token); } private RegexPrimaryExpressionNode ParseText() { var token = ConsumeCurrentToken(allowTrivia: true); Debug.Assert(token.Value == null); // Allow trivia between this piece of text and the next sequence element return new RegexTextNode(token.With(kind: RegexKind.TextToken)); } private RegexPrimaryExpressionNode ParseEndAnchor() { // Allow trivia between this anchor and the next sequence element return new RegexAnchorNode(RegexKind.EndAnchor, ConsumeCurrentToken(allowTrivia: true)); } private RegexPrimaryExpressionNode ParseStartAnchor() { // Allow trivia between this anchor and the next sequence element return new RegexAnchorNode(RegexKind.StartAnchor, ConsumeCurrentToken(allowTrivia: true)); } private RegexPrimaryExpressionNode ParseWildcard() { // Allow trivia between the . and the next sequence element return new RegexWildcardNode(ConsumeCurrentToken(allowTrivia: true)); } private RegexGroupingNode ParseGrouping() { var start = _lexer.Position; // Check what immediately follows the (. If we have (? it is processed specially. // However, we do not treat (? the same as ( ? var openParenToken = ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.QuestionToken: return ParseGroupQuestion(openParenToken, _currentToken); default: // Wasn't (? just parse this as a normal group. _lexer.Position = start; return ParseSimpleGroup(openParenToken); } } private RegexToken ParseGroupingCloseParen() { switch (_currentToken.Kind) { case RegexKind.CloseParenToken: // Grouping completed normally. Allow trivia between it and the next sequence element. return ConsumeCurrentToken(allowTrivia: true); default: return CreateMissingToken(RegexKind.CloseParenToken).AddDiagnosticIfNone( new EmbeddedDiagnostic(FeaturesResources.Not_enough_close_parens, GetTokenStartPositionSpan(_currentToken))); } } private RegexSimpleGroupingNode ParseSimpleGroup(RegexToken openParenToken) => new( openParenToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); private RegexExpressionNode ParseGroupingEmbeddedExpression(RegexOptions embeddedOptions) { // Save and restore options when we go into, and pop out of a group node. var currentOptions = _options; _options = embeddedOptions; // We're parsing the embedded sequence inside the current group. As this is a sequence // we want to allow trivia between the current token we're on, and the first token // of the embedded sequence. ConsumeCurrentToken(allowTrivia: true); // When parsing out the sequence don't grab the close paren, that will be for our caller // to get. var expression = this.ParseAlternatingSequences(consumeCloseParen: false); _options = currentOptions; return expression; } private TextSpan GetTokenSpanIncludingEOF(RegexToken token) => token.Kind == RegexKind.EndOfFile ? GetTokenStartPositionSpan(token) : token.GetSpan(); private TextSpan GetTokenStartPositionSpan(RegexToken token) { return token.Kind == RegexKind.EndOfFile ? new TextSpan(_lexer.Text.Last().Span.End, 0) : new TextSpan(token.VirtualChars[0].Span.Start, 0); } private RegexGroupingNode ParseGroupQuestion(RegexToken openParenToken, RegexToken questionToken) { var optionsToken = _lexer.TryScanOptions(); if (optionsToken != null) { return ParseOptionsGroupingNode(openParenToken, questionToken, optionsToken.Value); } var afterQuestionPos = _lexer.Position; // Lots of possible options when we see (?. Look at the immediately following character // (without any allowed spaces) to decide what to parse out next. ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.LessThanToken: // (?<=...) or (?<!...) or (?<...>...) or (?<...-...>...) return ParseLookbehindOrNamedCaptureOrBalancingGrouping(openParenToken, questionToken); case RegexKind.SingleQuoteToken: // (?'...'...) or (?'...-...'...) return ParseNamedCaptureOrBalancingGrouping( openParenToken, questionToken, _currentToken); case RegexKind.OpenParenToken: // alternation construct (?(...) | ) return ParseConditionalGrouping(openParenToken, questionToken); case RegexKind.ColonToken: return ParseNonCapturingGroupingNode(openParenToken, questionToken); case RegexKind.EqualsToken: return ParsePositiveLookaheadGrouping(openParenToken, questionToken); case RegexKind.ExclamationToken: return ParseNegativeLookaheadGrouping(openParenToken, questionToken); case RegexKind.GreaterThanToken: return ParseAtomicGrouping(openParenToken, questionToken); default: if (_currentToken.Kind != RegexKind.CloseParenToken) { // Native parser reports "Unrecognized grouping construct", *except* for (?) openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_grouping_construct, openParenToken.GetSpan())); } break; } // (?) // Parse this as a normal group. The question will immediately error as it's a // quantifier not following anything. _lexer.Position = afterQuestionPos - 1; return ParseSimpleGroup(openParenToken); } private RegexConditionalGroupingNode ParseConditionalGrouping(RegexToken openParenToken, RegexToken questionToken) { var innerOpenParenToken = _currentToken; var afterInnerOpenParen = _lexer.Position; var captureToken = _lexer.TryScanNumberOrCaptureName(); if (captureToken == null) { return ParseConditionalExpressionGrouping(openParenToken, questionToken); } var capture = captureToken.Value; RegexToken innerCloseParenToken; if (capture.Kind == RegexKind.NumberToken) { // If it's a numeric group, it has to be immediately followed by a ) and the // numeric reference has to exist. // // That means that (?(4 ) is not treated as an embedded expression but as an // error. This is different from (?(a ) which will be treated as an embedded // expression, and different from (?(a) will be treated as an embedded // expression or capture group depending on if 'a' is a existing capture name. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.CloseParenToken) { innerCloseParenToken = _currentToken; if (!HasCapture((int)capture.Value)) { capture = capture.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Reference_to_undefined_group, capture.GetSpan())); } } else { innerCloseParenToken = CreateMissingToken(RegexKind.CloseParenToken); capture = capture.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Malformed, capture.GetSpan())); MoveBackBeforePreviousScan(); } } else { // If it's a capture name, it's ok if that capture doesn't exist. In that case we // will just treat this as an conditional expression. if (!HasCapture((string)capture.Value)) { _lexer.Position = afterInnerOpenParen; return ParseConditionalExpressionGrouping(openParenToken, questionToken); } // Capture name existed. For this to be a capture grouping it exactly has to // match (?(a) anything other than a close paren after the ) will make this // into a conditional expression. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind != RegexKind.CloseParenToken) { _lexer.Position = afterInnerOpenParen; return ParseConditionalExpressionGrouping(openParenToken, questionToken); } innerCloseParenToken = _currentToken; } // Was (?(name) or (?(num) and name/num was a legal capture name. Parse // this out as a conditional grouping. Because we're going to be parsing out // an embedded sequence, allow trivia before the first element. ConsumeCurrentToken(allowTrivia: true); var result = ParseConditionalGroupingResult(); return new RegexConditionalCaptureGroupingNode( openParenToken, questionToken, innerOpenParenToken, capture, innerCloseParenToken, result, ParseGroupingCloseParen()); } private bool HasCapture(int value) => _captureNumbersToSpan.ContainsKey(value); private bool HasCapture(string value) => _captureNamesToSpan.ContainsKey(value); private void MoveBackBeforePreviousScan() { if (_currentToken.Kind != RegexKind.EndOfFile) { // Move back to un-consume whatever we just consumed. _lexer.Position--; } } private RegexConditionalGroupingNode ParseConditionalExpressionGrouping( RegexToken openParenToken, RegexToken questionToken) { // Reproduce very specific errors the .NET regex parser looks for. Technically, // we would error out in these cases no matter what. However, it means we can // stringently enforce that our parser produces the same errors as the native one. // // Move back before the ( _lexer.Position--; if (_lexer.IsAt("(?#")) { var pos = _lexer.Position; var comment = _lexer.ScanComment(options: default); _lexer.Position = pos; if (comment.Value.Diagnostics.Length > 0) { openParenToken = openParenToken.AddDiagnosticIfNone(comment.Value.Diagnostics[0]); } else { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Alternation_conditions_cannot_be_comments, openParenToken.GetSpan())); } } else if (_lexer.IsAt("(?'")) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named, openParenToken.GetSpan())); } else if (_lexer.IsAt("(?<")) { if (!_lexer.IsAt("(?<!") && !_lexer.IsAt("(?<=")) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named, openParenToken.GetSpan())); } } // Consume the ( once more. ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.Kind == RegexKind.OpenParenToken); // Parse out the grouping that starts with the second open paren in (?( // this will get us to (?(...) var grouping = ParseGrouping(); // Now parse out the embedded expression that follows that. this will get us to // (?(...)... var result = ParseConditionalGroupingResult(); // Finally, grab the close paren and produce (?(...)...) return new RegexConditionalExpressionGroupingNode( openParenToken, questionToken, grouping, result, ParseGroupingCloseParen()); } private RegexExpressionNode ParseConditionalGroupingResult() { var currentOptions = _options; var result = this.ParseAlternatingSequences(consumeCloseParen: false); _options = currentOptions; result = CheckConditionalAlternation(result); return result; } private static RegexExpressionNode CheckConditionalAlternation(RegexExpressionNode result) { if (result is RegexAlternationNode topAlternation && topAlternation.Left is RegexAlternationNode) { return new RegexAlternationNode( topAlternation.Left, topAlternation.BarToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Too_many_bars_in_conditional_grouping, topAlternation.BarToken.GetSpan())), topAlternation.Right); } return result; } private RegexGroupingNode ParseLookbehindOrNamedCaptureOrBalancingGrouping( RegexToken openParenToken, RegexToken questionToken) { var start = _lexer.Position; // We have (?< Look for (?<= or (?<! var lessThanToken = ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.EqualsToken: return new RegexPositiveLookbehindGroupingNode( openParenToken, questionToken, lessThanToken, _currentToken, ParseGroupingEmbeddedExpression(_options | RegexOptions.RightToLeft), ParseGroupingCloseParen()); case RegexKind.ExclamationToken: return new RegexNegativeLookbehindGroupingNode( openParenToken, questionToken, lessThanToken, _currentToken, ParseGroupingEmbeddedExpression(_options | RegexOptions.RightToLeft), ParseGroupingCloseParen()); default: // Didn't have a lookbehind group. Parse out as (?<...> or (?<...-...> _lexer.Position = start; return ParseNamedCaptureOrBalancingGrouping(openParenToken, questionToken, lessThanToken); } } private RegexGroupingNode ParseNamedCaptureOrBalancingGrouping( RegexToken openParenToken, RegexToken questionToken, RegexToken openToken) { if (_lexer.Position == _lexer.Text.Length) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_grouping_construct, GetSpan(openParenToken, openToken))); } // (?<...>...) or (?<...-...>...) // (?'...'...) or (?'...-...'...) var captureToken = _lexer.TryScanNumberOrCaptureName(); if (captureToken == null) { // Can't have any trivia between the elements in this grouping header. ConsumeCurrentToken(allowTrivia: false); captureToken = CreateMissingToken(RegexKind.CaptureNameToken); if (_currentToken.Kind == RegexKind.MinusToken) { return ParseBalancingGrouping( openParenToken, questionToken, openToken, captureToken.Value); } else { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character, GetTokenSpanIncludingEOF(_currentToken))); // If we weren't at the end of the text, go back to before whatever character // we just consumed. MoveBackBeforePreviousScan(); } } var capture = captureToken.Value; if (capture.Kind == RegexKind.NumberToken && (int)capture.Value == 0) { capture = capture.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Capture_number_cannot_be_zero, capture.GetSpan())); } // Can't have any trivia between the elements in this grouping header. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.MinusToken) { // Have (?<...- parse out the balancing group form. return ParseBalancingGrouping( openParenToken, questionToken, openToken, capture); } var closeToken = ParseCaptureGroupingCloseToken(ref openParenToken, openToken); return new RegexCaptureGroupingNode( openParenToken, questionToken, openToken, capture, closeToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); } private RegexToken ParseCaptureGroupingCloseToken(ref RegexToken openParenToken, RegexToken openToken) { if ((openToken.Kind == RegexKind.LessThanToken && _currentToken.Kind == RegexKind.GreaterThanToken) || (openToken.Kind == RegexKind.SingleQuoteToken && _currentToken.Kind == RegexKind.SingleQuoteToken)) { return _currentToken; } if (_currentToken.Kind == RegexKind.EndOfFile) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_grouping_construct, GetSpan(openParenToken, openToken))); } else { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character, _currentToken.GetSpan())); // Rewind to where we were before seeing this bogus character. _lexer.Position--; } return CreateMissingToken( openToken.Kind == RegexKind.LessThanToken ? RegexKind.GreaterThanToken : RegexKind.SingleQuoteToken); } private RegexBalancingGroupingNode ParseBalancingGrouping( RegexToken openParenToken, RegexToken questionToken, RegexToken openToken, RegexToken firstCapture) { var minusToken = _currentToken; var secondCapture = _lexer.TryScanNumberOrCaptureName(); if (secondCapture == null) { // Invalid group name: Group names must begin with a word character ConsumeCurrentToken(allowTrivia: false); openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character, GetTokenSpanIncludingEOF(_currentToken))); // If we weren't at the end of the text, go back to before whatever character // we just consumed. MoveBackBeforePreviousScan(); secondCapture = CreateMissingToken(RegexKind.CaptureNameToken); } var second = secondCapture.Value; CheckCapture(ref second); // Can't have any trivia between the elements in this grouping header. ConsumeCurrentToken(allowTrivia: false); var closeToken = ParseCaptureGroupingCloseToken(ref openParenToken, openToken); return new RegexBalancingGroupingNode( openParenToken, questionToken, openToken, firstCapture, minusToken, second, closeToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); } private void CheckCapture(ref RegexToken captureToken) { if (captureToken.IsMissing) { // Don't need to check for a synthesized error capture token. return; } if (captureToken.Kind == RegexKind.NumberToken) { var val = (int)captureToken.Value; if (!HasCapture(val)) { captureToken = captureToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Reference_to_undefined_group_number_0, val), captureToken.GetSpan())); } } else { var val = (string)captureToken.Value; if (!HasCapture(val)) { captureToken = captureToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Reference_to_undefined_group_name_0, val), captureToken.GetSpan())); } } } private RegexNonCapturingGroupingNode ParseNonCapturingGroupingNode(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); private RegexPositiveLookaheadGroupingNode ParsePositiveLookaheadGrouping(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options & ~RegexOptions.RightToLeft), ParseGroupingCloseParen()); private RegexNegativeLookaheadGroupingNode ParseNegativeLookaheadGrouping(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options & ~RegexOptions.RightToLeft), ParseGroupingCloseParen()); private RegexAtomicGroupingNode ParseAtomicGrouping(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); private RegexGroupingNode ParseOptionsGroupingNode( RegexToken openParenToken, RegexToken questionToken, RegexToken optionsToken) { // Only (?opts:...) or (?opts) are allowed. After the opts must be a : or ) ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.CloseParenToken: // Allow trivia after the options and the next element in the sequence. _options = GetNewOptionsFromToken(_options, optionsToken); return new RegexSimpleOptionsGroupingNode( openParenToken, questionToken, optionsToken, ConsumeCurrentToken(allowTrivia: true)); case RegexKind.ColonToken: return ParseNestedOptionsGroupingNode(openParenToken, questionToken, optionsToken); default: return new RegexSimpleOptionsGroupingNode( openParenToken, questionToken, optionsToken, CreateMissingToken(RegexKind.CloseParenToken).AddDiagnosticIfNone( new EmbeddedDiagnostic(FeaturesResources.Unrecognized_grouping_construct, openParenToken.GetSpan()))); } } private RegexNestedOptionsGroupingNode ParseNestedOptionsGroupingNode( RegexToken openParenToken, RegexToken questionToken, RegexToken optionsToken) => new( openParenToken, questionToken, optionsToken, _currentToken, ParseGroupingEmbeddedExpression(GetNewOptionsFromToken(_options, optionsToken)), ParseGroupingCloseParen()); private static bool IsTextChar(RegexToken currentToken, char ch) => currentToken.Kind == RegexKind.TextToken && currentToken.VirtualChars.Length == 1 && currentToken.VirtualChars[0].Value == ch; private static RegexOptions GetNewOptionsFromToken(RegexOptions currentOptions, RegexToken optionsToken) { var copy = currentOptions; var on = true; foreach (var ch in optionsToken.VirtualChars) { switch (ch.Value) { case '-': on = false; break; case '+': on = true; break; default: var newOption = OptionFromCode(ch); if (on) { copy |= newOption; } else { copy &= ~newOption; } break; } } return copy; } private static RegexOptions OptionFromCode(VirtualChar ch) { switch (ch.Value) { case 'i': case 'I': return RegexOptions.IgnoreCase; case 'm': case 'M': return RegexOptions.Multiline; case 'n': case 'N': return RegexOptions.ExplicitCapture; case 's': case 'S': return RegexOptions.Singleline; case 'x': case 'X': return RegexOptions.IgnorePatternWhitespace; default: throw new InvalidOperationException(); } } private RegexBaseCharacterClassNode ParseCharacterClass() { var openBracketToken = _currentToken; Debug.Assert(openBracketToken.Kind == RegexKind.OpenBracketToken); var caretToken = CreateMissingToken(RegexKind.CaretToken); var closeBracketToken = CreateMissingToken(RegexKind.CloseBracketToken); // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.CaretToken) { caretToken = _currentToken; } else { MoveBackBeforePreviousScan(); } // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); using var _1 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var builder); while (_currentToken.Kind != RegexKind.EndOfFile) { Debug.Assert(_currentToken.VirtualChars.Length == 1); if (_currentToken.Kind == RegexKind.CloseBracketToken && builder.Count > 0) { // Allow trivia after the character class, and whatever is next in the sequence. closeBracketToken = ConsumeCurrentToken(allowTrivia: true); break; } ParseCharacterClassComponents(builder); } // We wil commonly get tons of text nodes in a row. For example, the // regex `[abc]` will be three text nodes in a row. To help save on memory // try to merge that into one single text node. using var _2 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var contents); MergeTextNodes(builder, contents); if (closeBracketToken.IsMissing) { closeBracketToken = closeBracketToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unterminated_character_class_set, GetTokenStartPositionSpan(_currentToken))); } var components = new RegexSequenceNode(contents.ToImmutable()); return caretToken.IsMissing ? (RegexBaseCharacterClassNode)new RegexCharacterClassNode(openBracketToken, components, closeBracketToken) : new RegexNegatedCharacterClassNode(openBracketToken, caretToken, components, closeBracketToken); } private void ParseCharacterClassComponents(ArrayBuilder<RegexExpressionNode> components) { var left = ParseSingleCharacterClassComponent(isFirst: components.Count == 0, afterRangeMinus: false); if (left.Kind == RegexKind.CharacterClassEscape || left.Kind == RegexKind.CategoryEscape || IsEscapedMinus(left)) { // \s or \p{Lu} or \- on the left of a minus doesn't start a range. If there is a following // minus, it's just treated textually. components.Add(left); return; } if (_currentToken.Kind == RegexKind.MinusToken && !_lexer.IsAt("]")) { // trivia is not allowed anywhere in a character class var minusToken = ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.OpenBracketToken) { components.Add(left); components.Add(ParseCharacterClassSubtractionNode(minusToken)); } else { // Note that behavior of parsing here changed in .net. See issue: // https://github.com/dotnet/corefx/issues/31786 // // We follow the latest behavior in .net which parses things correctly. var right = ParseSingleCharacterClassComponent(isFirst: false, afterRangeMinus: true); if (TryGetRangeComponentValue(left, out var leftCh) && TryGetRangeComponentValue(right, out var rightCh) && leftCh > rightCh) { minusToken = minusToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.x_y_range_in_reverse_order, minusToken.GetSpan())); } components.Add(new RegexCharacterClassRangeNode(left, minusToken, right)); } } else { components.Add(left); } } private static bool IsEscapedMinus(RegexNode node) => node is RegexSimpleEscapeNode simple && IsTextChar(simple.TypeToken, '-'); private bool TryGetRangeComponentValue(RegexExpressionNode component, out int ch) { // Don't bother examining the component if it has any errors already. This also means // we don't have to worry about running into invalid escape sequences and the like. if (!HasProblem(component)) { return TryGetRangeComponentValueWorker(component, out ch); } ch = default; return false; } private bool TryGetRangeComponentValueWorker(RegexNode component, out int ch) { switch (component.Kind) { case RegexKind.SimpleEscape: var escapeNode = (RegexSimpleEscapeNode)component; ch = MapEscapeChar(escapeNode.TypeToken.VirtualChars[0]).Value; return true; case RegexKind.ControlEscape: var controlEscape = (RegexControlEscapeNode)component; var controlCh = controlEscape.ControlToken.VirtualChars[0].Value; // \ca interpreted as \cA if (controlCh is >= 'a' and <= 'z') { controlCh -= (char)('a' - 'A'); } // The control characters have values mapping from the A-Z range to numeric // values 1-26. So, to map that, we subtract 'A' from the value (which would // give us 0-25) and then add '1' back to it. ch = controlCh - 'A' + 1; return true; case RegexKind.OctalEscape: ch = GetCharValue(((RegexOctalEscapeNode)component).OctalText, withBase: 8); return true; case RegexKind.HexEscape: ch = GetCharValue(((RegexHexEscapeNode)component).HexText, withBase: 16); return true; case RegexKind.UnicodeEscape: ch = GetCharValue(((RegexUnicodeEscapeNode)component).HexText, withBase: 16); return true; case RegexKind.PosixProperty: // When the native parser sees [:...:] it treats this as if it just saw '[' and skipped the // rest. ch = '['; return true; case RegexKind.Text: ch = ((RegexTextNode)component).TextToken.VirtualChars[0].Value; return true; case RegexKind.Sequence: var sequence = (RegexSequenceNode)component; #if DEBUG Debug.Assert(sequence.ChildCount > 0); for (int i = 0, n = sequence.ChildCount - 1; i < n; i++) { Debug.Assert(IsEscapedMinus(sequence.ChildAt(i).Node)); } #endif var last = sequence.ChildAt(sequence.ChildCount - 1).Node; if (IsEscapedMinus(last)) { break; } return TryGetRangeComponentValueWorker(last, out ch); } ch = default; return false; } private static int GetCharValue(RegexToken hexText, int withBase) { unchecked { var total = 0; foreach (var vc in hexText.VirtualChars) { total *= withBase; total += HexValue(vc); } return total; } } private static int HexValue(VirtualChar ch) { Debug.Assert(RegexLexer.IsHexChar(ch)); unchecked { var temp = ch.Value - '0'; if (temp is >= 0 and <= 9) return temp; temp = ch.Value - 'a'; if (temp is >= 0 and <= 5) return temp + 10; temp = ch.Value - 'A'; if (temp is >= 0 and <= 5) return temp + 10; } throw new InvalidOperationException(); } private bool HasProblem(RegexNodeOrToken component) { if (component.IsNode) { foreach (var child in component.Node) { if (HasProblem(child)) { return true; } } } else { var token = component.Token; if (token.IsMissing || token.Diagnostics.Length > 0) { return true; } foreach (var trivia in token.LeadingTrivia) { if (trivia.Diagnostics.Length > 0) { return true; } } } return false; } private RegexPrimaryExpressionNode ParseSingleCharacterClassComponent(bool isFirst, bool afterRangeMinus) { if (_currentToken.Kind == RegexKind.BackslashToken && _lexer.Position < _lexer.Text.Length) { var backslashToken = _currentToken; // trivia is not allowed anywhere in a character class, and definitely not between // a \ and the following character. ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.VirtualChars.Length == 1); var nextChar = _currentToken.VirtualChars[0]; switch (nextChar.Value) { case 'D': case 'd': case 'S': case 's': case 'W': case 'w': case 'p': case 'P': if (afterRangeMinus) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, nextChar), GetSpan(backslashToken, _currentToken))); } // move back before the character we just scanned. // trivia is not allowed anywhere in a character class. // The above list are character class and category escapes. ParseEscape can // handle both of those, so we just defer to it. _lexer.Position--; return ParseEscape(backslashToken, allowTriviaAfterEnd: false); case '-': // trivia is not allowed anywhere in a character class. // We just let the basic consumption code pull out a token for us, we then // convert that to text since we treat all characters after the - as text no // matter what. return new RegexSimpleEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: false).With(kind: RegexKind.TextToken)); default: // trivia is not allowed anywhere in a character class. // Note: it is very intentional that we're calling ParseCharEscape and not // ParseEscape. Normal escapes are not interpreted the same way inside a // character class. For example \b is not an anchor in a character class. // And things like \k'...' are not k-captures, etc. etc. _lexer.Position--; return ParseCharEscape(backslashToken, allowTriviaAfterEnd: false); } } if (!afterRangeMinus && !isFirst && _currentToken.Kind == RegexKind.MinusToken && _lexer.IsAt("[")) { // have a trailing subtraction. // trivia is not allowed anywhere in a character class return ParseCharacterClassSubtractionNode( ConsumeCurrentToken(allowTrivia: false)); } // From the .NET regex code: // This is code for Posix style properties - [:Ll:] or [:IsTibetan:]. // It currently doesn't do anything other than skip the whole thing! if (!afterRangeMinus && _currentToken.Kind == RegexKind.OpenBracketToken && _lexer.IsAt(":")) { var beforeBracketPos = _lexer.Position - 1; // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); var captureName = _lexer.TryScanCaptureName(); if (captureName.HasValue && _lexer.IsAt(":]")) { _lexer.Position += 2; var textChars = _lexer.GetSubPattern(beforeBracketPos, _lexer.Position); var token = CreateToken(RegexKind.TextToken, ImmutableArray<RegexTrivia>.Empty, textChars); // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); return new RegexPosixPropertyNode(token); } else { // Reset to back where we were. // trivia is not allowed anywhere in a character class _lexer.Position = beforeBracketPos; ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.Kind == RegexKind.OpenBracketToken); } } // trivia is not allowed anywhere in a character class return new RegexTextNode( ConsumeCurrentToken(allowTrivia: false).With(kind: RegexKind.TextToken)); } private RegexPrimaryExpressionNode ParseCharacterClassSubtractionNode(RegexToken minusToken) { var charClass = ParseCharacterClass(); if (_currentToken.Kind is not RegexKind.CloseBracketToken and not RegexKind.EndOfFile) { minusToken = minusToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class, GetTokenStartPositionSpan(minusToken))); } return new RegexCharacterClassSubtractionNode(minusToken, charClass); } /// <summary> /// Parses out an escape sequence. Escape sequences are allowed in top level sequences /// and in character classes. In a top level sequence trivia will be allowed afterwards, /// but in a character class trivia is not allowed afterwards. /// </summary> private RegexEscapeNode ParseEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); // No spaces between \ and next char. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.EndOfFile) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Illegal_backslash_at_end_of_pattern, backslashToken.GetSpan())); return new RegexSimpleEscapeNode(backslashToken, CreateMissingToken(RegexKind.TextToken)); } Debug.Assert(_currentToken.VirtualChars.Length == 1); switch (_currentToken.VirtualChars[0].Value) { case 'b': case 'B': case 'A': case 'G': case 'Z': case 'z': return new RegexAnchorEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd)); case 'w': case 'W': case 's': case 'S': case 'd': case 'D': return new RegexCharacterClassEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd)); case 'p': case 'P': return ParseCategoryEscape(backslashToken, allowTriviaAfterEnd); } // Move back to after the backslash _lexer.Position--; return ParseBasicBackslash(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParseBasicBackslash(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); // No spaces between \ and next char. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.EndOfFile) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Illegal_backslash_at_end_of_pattern, backslashToken.GetSpan())); return new RegexSimpleEscapeNode(backslashToken, CreateMissingToken(RegexKind.TextToken)); } Debug.Assert(_currentToken.VirtualChars.Length == 1); var ch = _currentToken.VirtualChars[0]; if (ch == 'k') { return ParsePossibleKCaptureEscape(backslashToken, allowTriviaAfterEnd); } if (ch.Value is '<' or '\'') { _lexer.Position--; return ParsePossibleCaptureEscape(backslashToken, allowTriviaAfterEnd); } if (ch.Value is >= '1' and <= '9') { _lexer.Position--; return ParsePossibleBackreferenceEscape(backslashToken, allowTriviaAfterEnd); } _lexer.Position--; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleBackreferenceEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); return HasOption(_options, RegexOptions.ECMAScript) ? ParsePossibleEcmascriptBackreferenceEscape(backslashToken, allowTriviaAfterEnd) : ParsePossibleRegularBackreferenceEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleEcmascriptBackreferenceEscape( RegexToken backslashToken, bool allowTriviaAfterEnd) { // Small deviation: Ecmascript allows references only to captures that precede // this position (unlike .NET which allows references in any direction). However, // because we don't track position, we just consume the entire back-reference. // // This is addressable if we add position tracking when we locate all the captures. Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); var start = _lexer.Position; var bestPosition = -1; var capVal = 0; while (_lexer.Position < _lexer.Text.Length && _lexer.Text[_lexer.Position] is var ch && (ch >= '0' && ch <= '9')) { unchecked { capVal *= 10; capVal += (ch.Value - '0'); } _lexer.Position++; if (HasCapture(capVal)) { bestPosition = _lexer.Position; } } if (bestPosition != -1) { var numberToken = CreateToken( RegexKind.NumberToken, ImmutableArray<RegexTrivia>.Empty, _lexer.GetSubPattern(start, bestPosition)).With(value: capVal); ResetToPositionAndConsumeCurrentToken(bestPosition, allowTrivia: allowTriviaAfterEnd); return new RegexBackreferenceEscapeNode(backslashToken, numberToken); } _lexer.Position = start; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleRegularBackreferenceEscape( RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); var start = _lexer.Position; var numberToken = _lexer.TryScanNumber().Value; var capVal = (int)numberToken.Value; if (HasCapture(capVal) || capVal <= 9) { CheckCapture(ref numberToken); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexBackreferenceEscapeNode(backslashToken, numberToken); } _lexer.Position = start; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleCaptureEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); Debug.Assert(_lexer.Text[_lexer.Position].Value is '<' or '\''); var afterBackslashPosition = _lexer.Position; ScanCaptureParts(allowTriviaAfterEnd, out var openToken, out var capture, out var closeToken); if (openToken.IsMissing || capture.IsMissing || closeToken.IsMissing) { _lexer.Position = afterBackslashPosition; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } return new RegexCaptureEscapeNode( backslashToken, openToken, capture, closeToken); } private RegexEscapeNode ParsePossibleKCaptureEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { var typeToken = _currentToken; var afterBackslashPosition = _lexer.Position - @"k".Length; ScanCaptureParts(allowTriviaAfterEnd, out var openToken, out var capture, out var closeToken); if (openToken.IsMissing) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Malformed_named_back_reference, GetSpan(backslashToken, typeToken))); return new RegexSimpleEscapeNode(backslashToken, typeToken.With(kind: RegexKind.TextToken)); } if (capture.IsMissing || closeToken.IsMissing) { // Native parser falls back to normal escape scanning, if it doesn't see a capture, // or close brace. For normal .NET regexes, this will then fail later (as \k is not // a legal escape), but will succeed for ecmascript regexes. _lexer.Position = afterBackslashPosition; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } return new RegexKCaptureEscapeNode( backslashToken, typeToken, openToken, capture, closeToken); } private void ScanCaptureParts( bool allowTriviaAfterEnd, out RegexToken openToken, out RegexToken capture, out RegexToken closeToken) { openToken = CreateMissingToken(RegexKind.LessThanToken); capture = CreateMissingToken(RegexKind.CaptureNameToken); closeToken = CreateMissingToken(RegexKind.GreaterThanToken); // No trivia allowed in <cap> or 'cap' ConsumeCurrentToken(allowTrivia: false); if (_lexer.Position < _lexer.Text.Length && (_currentToken.Kind == RegexKind.LessThanToken || _currentToken.Kind == RegexKind.SingleQuoteToken)) { openToken = _currentToken; } else { return; } var captureToken = _lexer.TryScanNumberOrCaptureName(); capture = captureToken == null ? CreateMissingToken(RegexKind.CaptureNameToken) : captureToken.Value; // No trivia allowed in <cap> or 'cap' ConsumeCurrentToken(allowTrivia: false); closeToken = CreateMissingToken(RegexKind.GreaterThanToken); if (!capture.IsMissing && ((openToken.Kind == RegexKind.LessThanToken && _currentToken.Kind == RegexKind.GreaterThanToken) || (openToken.Kind == RegexKind.SingleQuoteToken && _currentToken.Kind == RegexKind.SingleQuoteToken))) { CheckCapture(ref capture); closeToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); } } private RegexEscapeNode ParseCharEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); // no trivia between \ and the next char ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.VirtualChars.Length == 1); var ch = _currentToken.VirtualChars[0]; if (ch.Value is >= '0' and <= '7') { _lexer.Position--; var octalDigits = _lexer.ScanOctalCharacters(_options); Debug.Assert(octalDigits.VirtualChars.Length > 0); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexOctalEscapeNode(backslashToken, octalDigits); } switch (ch.Value) { case 'a': case 'b': case 'e': case 'f': case 'n': case 'r': case 't': case 'v': return new RegexSimpleEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd)); case 'x': return ParseHexEscape(backslashToken, allowTriviaAfterEnd); case 'u': return ParseUnicodeEscape(backslashToken, allowTriviaAfterEnd); case 'c': return ParseControlEscape(backslashToken, allowTriviaAfterEnd); default: var typeToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd).With(kind: RegexKind.TextToken); if (!HasOption(_options, RegexOptions.ECMAScript) && RegexCharClass.IsWordChar(ch)) { typeToken = typeToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Unrecognized_escape_sequence_0, ch), typeToken.GetSpan())); } return new RegexSimpleEscapeNode(backslashToken, typeToken); } } private RegexEscapeNode ParseUnicodeEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { var typeToken = _currentToken; var hexChars = _lexer.ScanHexCharacters(4); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexUnicodeEscapeNode(backslashToken, typeToken, hexChars); } private RegexEscapeNode ParseHexEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { var typeToken = _currentToken; var hexChars = _lexer.ScanHexCharacters(2); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexHexEscapeNode(backslashToken, typeToken, hexChars); } private RegexControlEscapeNode ParseControlEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { // Nothing allowed between \c and the next char var typeToken = ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.EndOfFile) { typeToken = typeToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Missing_control_character, typeToken.GetSpan())); return new RegexControlEscapeNode(backslashToken, typeToken, CreateMissingToken(RegexKind.TextToken)); } Debug.Assert(_currentToken.VirtualChars.Length == 1); var ch = _currentToken.VirtualChars[0].Value; unchecked { // From: https://github.com/dotnet/corefx/blob/80e220fc7009de0f0611ee6b52d4d5ffd25eb6c7/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs#L1450 // Note: Roslyn accepts a control escape that current .NET parser does not. // Specifically: \c[ // // It is a bug that the .NET parser does not support this construct. The bug was // reported at: https://github.com/dotnet/corefx/issues/26501 and was fixed for // CoreFx with https://github.com/dotnet/corefx/commit/80e220fc7009de0f0611ee6b52d4d5ffd25eb6c7 // // Because it was a bug, we follow the correct behavior. That means we will not // report a diagnostic for a Regex that someone might run on a previous version of // .NET that ends up throwing at runtime. That's acceptable. Our goal is to match // the latest .NET 'correct' behavior. Not intermediary points with bugs that have // since been fixed. // \ca interpreted as \cA if (ch is >= 'a' and <= 'z') { ch -= (char)('a' - 'A'); } if (ch is >= '@' and <= '_') { var controlToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd).With(kind: RegexKind.TextToken); return new RegexControlEscapeNode(backslashToken, typeToken, controlToken); } else { typeToken = typeToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_control_character, _currentToken.GetSpan())); // Don't consume the bogus control character. return new RegexControlEscapeNode(backslashToken, typeToken, CreateMissingToken(RegexKind.TextToken)); } } } private RegexEscapeNode ParseCategoryEscape(RegexToken backslash, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] is var ch && (ch == 'P' || ch == 'p')); var typeToken = _currentToken; var start = _lexer.Position; if (!TryGetCategoryEscapeParts( allowTriviaAfterEnd, out var openBraceToken, out var categoryToken, out var closeBraceToken, out var message)) { ResetToPositionAndConsumeCurrentToken(start, allowTrivia: allowTriviaAfterEnd); typeToken = typeToken.With(kind: RegexKind.TextToken).AddDiagnosticIfNone(new EmbeddedDiagnostic( message, GetSpan(backslash, typeToken))); return new RegexSimpleEscapeNode(backslash, typeToken); } return new RegexCategoryEscapeNode(backslash, typeToken, openBraceToken, categoryToken, closeBraceToken); } private bool TryGetCategoryEscapeParts( bool allowTriviaAfterEnd, out RegexToken openBraceToken, out RegexToken categoryToken, out RegexToken closeBraceToken, out string message) { openBraceToken = default; categoryToken = default; closeBraceToken = default; message = null; if (_lexer.Text.Length - _lexer.Position < "{x}".Length) { message = FeaturesResources.Incomplete_character_escape; return false; } // no whitespace in \p{x} ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind != RegexKind.OpenBraceToken) { message = FeaturesResources.Malformed_character_escape; return false; } openBraceToken = _currentToken; var category = _lexer.TryScanEscapeCategory(); // no whitespace in \p{x} ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind != RegexKind.CloseBraceToken) { message = FeaturesResources.Incomplete_character_escape; return false; } if (category == null) { message = FeaturesResources.Unknown_property; return false; } categoryToken = category.Value; closeBraceToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return true; } private RegexTextNode ParseUnexpectedQuantifier(RegexExpressionNode lastExpression) { // This is just a bogus element in the higher level sequence. Allow trivia // after this to abide by the spirit of the native parser. var token = ConsumeCurrentToken(allowTrivia: true); CheckQuantifierExpression(lastExpression, ref token); return new RegexTextNode(token.With(kind: RegexKind.TextToken)); } private static void CheckQuantifierExpression(RegexExpressionNode current, ref RegexToken token) { if (current == null || current.Kind == RegexKind.SimpleOptionsGrouping) { token = token.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Quantifier_x_y_following_nothing, token.GetSpan())); } else if (current is RegexQuantifierNode or RegexLazyQuantifierNode) { token = token.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Nested_quantifier_0, token.VirtualChars.First()), token.GetSpan())); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { using static EmbeddedSyntaxHelpers; using static RegexHelpers; using RegexNodeOrToken = EmbeddedSyntaxNodeOrToken<RegexKind, RegexNode>; using RegexToken = EmbeddedSyntaxToken<RegexKind>; using RegexTrivia = EmbeddedSyntaxTrivia<RegexKind>; /// <summary> /// Produces a <see cref="RegexTree"/> from a sequence of <see cref="VirtualChar"/> characters. /// /// Importantly, this parser attempts to replicate diagnostics with almost the exact same text /// as the native .NET regex parser. This is important so that users get an understandable /// experience where it appears to them that this is all one cohesive system and that the IDE /// will let them discover and fix the same issues they would encounter when previously trying /// to just compile and execute these regexes. /// </summary> /// <remarks> /// Invariants we try to maintain (and should consider a bug if we do not): l 1. If the .NET /// regex parser does not report an error for a given pattern, we should not either. it would be /// very bad if we told the user there was something wrong with there pattern when there really /// wasn't. /// /// 2. If the .NET regex parser does report an error for a given pattern, we should either not /// report an error (not recommended) or report the same error at an appropriate location in the /// pattern. Not reporting the error can be confusing as the user will think their pattern is /// ok, when it really is not. However, it can be acceptable to do this as it's not telling /// them that something is actually wrong, and it may be too difficult to find and report the /// same error. Note: there is only one time we do this in this parser (see the deviation /// documented in <see cref="ParsePossibleEcmascriptBackreferenceEscape"/>). /// /// Note1: "report the same error" means that we will attempt to report the error using the same /// text the .NET regex parser uses for its error messages. This is so that the user is not /// confused when they use the IDE vs running the regex by getting different messages for the /// same issue. /// /// Note2: the above invariants make life difficult at times. This happens due to the fact that /// the .NET parser is multi-pass. Meaning it does a first scan (which may report errors), then /// does the full parse. This means that it might report an error in a later location during /// the initial scan than it would during the parse. We replicate that behavior to follow the /// second invariant. /// /// Note3: It would be nice if we could check these invariants at runtime, so we could control /// our behavior by the behavior of the real .NET regex engine. For example, if the .NET regex /// engine did not report any issues, we could suppress any diagnostics we generated and we /// could log an NFW to record which pattern we deviated on so we could fix the issue for a /// future release. However, we cannot do this as the .NET regex engine has no guarantees about /// its performance characteristics. For example, certain regex patterns might end up causing /// that engine to consume unbounded amounts of CPU and memory. This is because the .NET regex /// engine is not just a parser, but something that builds an actual recognizer using techniques /// that are not necessarily bounded. As such, while we test ourselves around it during our /// tests, we cannot do the same at runtime as part of the IDE. /// /// This parser was based off the corefx RegexParser based at: /// https://github.com/dotnet/corefx/blob/f759243d724f462da0bcef54e86588f8a55352c6/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs#L1 /// /// Note4: The .NET parser itself changes over time (for example to fix behavior that even it /// thinks is buggy). When this happens, we have to make a choice as to which behavior to /// follow. In general, the overall principle is that we should follow the more lenient /// behavior. If we end up taking the more strict interpretation we risk giving people an error /// during design time that they would not get at runtime. It's far worse to have that than to /// not report an error, even though one might happen later. /// </remarks> internal partial struct RegexParser { private readonly ImmutableDictionary<string, TextSpan> _captureNamesToSpan; private readonly ImmutableDictionary<int, TextSpan> _captureNumbersToSpan; private RegexLexer _lexer; private RegexOptions _options; private RegexToken _currentToken; private int _recursionDepth; private RegexParser( VirtualCharSequence text, RegexOptions options, ImmutableDictionary<string, TextSpan> captureNamesToSpan, ImmutableDictionary<int, TextSpan> captureNumbersToSpan) : this() { _lexer = new RegexLexer(text); _options = options; _captureNamesToSpan = captureNamesToSpan; _captureNumbersToSpan = captureNumbersToSpan; // Get the first token. It is allowed to have trivia on it. ConsumeCurrentToken(allowTrivia: true); } /// <summary> /// Returns the latest token the lexer has produced, and then asks the lexer to /// produce the next token after that. /// </summary> /// <param name="allowTrivia">Whether or not trivia is allowed on the next token /// produced. In the .NET parser trivia is only allowed on a few constructs, /// and our parser mimics that behavior. Note that even if trivia is allowed, /// the type of trivia that can be scanned depends on the current RegexOptions. /// For example, if <see cref="RegexOptions.IgnorePatternWhitespace"/> is currently /// enabled, then '#...' comments are allowed. Otherwise, only '(?#...)' comments /// are allowed.</param> private RegexToken ConsumeCurrentToken(bool allowTrivia) { var previous = _currentToken; _currentToken = _lexer.ScanNextToken(allowTrivia, _options); return previous; } /// <summary> /// Given an input text, and set of options, parses out a fully representative syntax tree /// and list of diagnostics. Parsing should always succeed, except in the case of the stack /// overflowing. /// </summary> public static RegexTree TryParse(VirtualCharSequence text, RegexOptions options) { if (text.IsDefault) { return null; } try { // Parse the tree once, to figure out the capture groups. These are needed // to then parse the tree again, as the captures will affect how we interpret // certain things (i.e. escape references) and what errors will be reported. // // This is necessary as .NET regexes allow references to *future* captures. // As such, we don't know when we're seeing a reference if it's to something // that exists or not. var tree1 = new RegexParser(text, options, ImmutableDictionary<string, TextSpan>.Empty, ImmutableDictionary<int, TextSpan>.Empty).ParseTree(); var (captureNames, captureNumbers) = CaptureInfoAnalyzer.Analyze(text, tree1.Root, options); var tree2 = new RegexParser( text, options, captureNames, captureNumbers).ParseTree(); return tree2; } catch (InsufficientExecutionStackException) { return null; } } private RegexTree ParseTree() { // Most callers to ParseAlternatingSequences are from group constructs. As those // constructs will have already consumed the open paren, they don't want this sub-call // to consume through close-paren tokens as they want that token for themselves. // However, we're the topmost call and have not consumed an open paren. And, we want // this call to consume all the way to the end, eating up excess close-paren tokens that // are encountered. var expression = this.ParseAlternatingSequences(consumeCloseParen: true); Debug.Assert(_lexer.Position == _lexer.Text.Length); Debug.Assert(_currentToken.Kind == RegexKind.EndOfFile); var root = new RegexCompilationUnit(expression, _currentToken); var seenDiagnostics = new HashSet<EmbeddedDiagnostic>(); using var _ = ArrayBuilder<EmbeddedDiagnostic>.GetInstance(out var diagnostics); CollectDiagnostics(root, seenDiagnostics, diagnostics); return new RegexTree( _lexer.Text, root, diagnostics.ToImmutable(), _captureNamesToSpan, _captureNumbersToSpan); } private static void CollectDiagnostics( RegexNode node, HashSet<EmbeddedDiagnostic> seenDiagnostics, ArrayBuilder<EmbeddedDiagnostic> diagnostics) { foreach (var child in node) { if (child.IsNode) { CollectDiagnostics(child.Node, seenDiagnostics, diagnostics); } else { var token = child.Token; foreach (var trivia in token.LeadingTrivia) { AddUniqueDiagnostics(seenDiagnostics, trivia.Diagnostics, diagnostics); } // We never place trailing trivia on regex tokens. Debug.Assert(token.TrailingTrivia.IsEmpty); AddUniqueDiagnostics(seenDiagnostics, token.Diagnostics, diagnostics); } } } /// <summary> /// It's very common to have duplicated diagnostics. For example, consider "((". This will /// have two 'missing )' diagnostics, both at the end. Reporting both isn't helpful, so we /// filter duplicates out here. /// </summary> private static void AddUniqueDiagnostics( HashSet<EmbeddedDiagnostic> seenDiagnostics, ImmutableArray<EmbeddedDiagnostic> from, ArrayBuilder<EmbeddedDiagnostic> to) { foreach (var diagnostic in from) { if (seenDiagnostics.Add(diagnostic)) { to.Add(diagnostic); } } } private RegexExpressionNode ParseAlternatingSequences(bool consumeCloseParen) { try { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); return ParseAlternatingSequencesWorker(consumeCloseParen); } finally { _recursionDepth--; } } /// <summary> /// Parses out code of the form: ...|...|... /// This is the type of code you have at the top level of a regex, or inside any grouping /// contruct. Note that sequences can be empty in .NET regex. i.e. the following is legal: /// /// ...||... /// /// An empty sequence just means "match at every position in the test string". /// </summary> private RegexExpressionNode ParseAlternatingSequencesWorker(bool consumeCloseParen) { RegexExpressionNode current = ParseSequence(consumeCloseParen); while (_currentToken.Kind == RegexKind.BarToken) { // Trivia allowed between the | and the next token. current = new RegexAlternationNode( current, ConsumeCurrentToken(allowTrivia: true), ParseSequence(consumeCloseParen)); } return current; } private RegexSequenceNode ParseSequence(bool consumeCloseParen) { using var _1 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var builder); while (ShouldConsumeSequenceElement(consumeCloseParen)) { var last = builder.Count == 0 ? null : builder.Last(); builder.Add(ParsePrimaryExpressionAndQuantifiers(last)); } // We wil commonly get tons of text nodes in a row. For example, the // regex `abc` will be three text nodes in a row. To help save on memory // try to merge that into one single text node. using var _2 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var sequence); MergeTextNodes(builder, sequence); return new RegexSequenceNode(sequence.ToImmutable()); } private static void MergeTextNodes(ArrayBuilder<RegexExpressionNode> list, ArrayBuilder<RegexExpressionNode> final) { // Iterate all the nodes in the sequence we have, adding them directly to // `final` if they are not text nodes. If they are text nodes, we attempt // to keep merging them with any following text nodes as long as well. for (var index = 0; index < list.Count;) { var current = list[index]; if (current.Kind != RegexKind.Text) { // Not a text node. Just add as-is, and move to the next node. index++; final.Add(current); continue; } // Got a text node. Try to combine it with all following nodes. index = MergeAndAddAdjacentTextNodes(list, final, index); } return; // local functions static int MergeAndAddAdjacentTextNodes( ArrayBuilder<RegexExpressionNode> list, ArrayBuilder<RegexExpressionNode> final, int index) { var startIndex = index; var startTextNode = (RegexTextNode)list[startIndex]; // Keep walking forward as long as we hit text nodes and we can // merge that text node with the previous text node. index++; var lastTextNode = startTextNode; for (; index < list.Count; index++) { var currentNode = list[index]; if (!CanMerge(lastTextNode, currentNode)) { // Hit something we couldn't merge with our last text node // Break out and merge what we have so far. 'index' will // be pointing at the right node for our caller. break; } lastTextNode = (RegexTextNode)currentNode; } // If didn't have multiple text nodes in a row. Just return the // starting node. Otherwise, create one text node that has a token // that spans from the start of the first node to the end of the last node. final.Add(startTextNode == lastTextNode ? startTextNode : new RegexTextNode(CreateToken( RegexKind.TextToken, startTextNode.TextToken.LeadingTrivia, VirtualCharSequence.FromBounds( startTextNode.TextToken.VirtualChars, lastTextNode.TextToken.VirtualChars)))); return index; } // Local functions static bool CanMerge(RegexTextNode lastNode, RegexExpressionNode next) { if (next.Kind == RegexKind.Text) { var lastTextToken = lastNode.TextToken; var nextTextToken = ((RegexTextNode)next).TextToken; // Can't merge if the next text node has leading trivia. Also, conservatively // don't allow merging if there are diagnostics or values for these tokens. // We might be able to support that, but it's easier to not do anything that // might break an expectation someone might have downstream. / if (lastTextToken.Diagnostics.Length == 0 && nextTextToken.Diagnostics.Length == 0 && lastTextToken.Value == null && nextTextToken.Value == null && nextTextToken.LeadingTrivia.Length == 0) { lastTextToken.VirtualChars.AssertAdjacentTo(nextTextToken.VirtualChars); return true; } } return false; } } private bool ShouldConsumeSequenceElement(bool consumeCloseParen) { if (_currentToken.Kind == RegexKind.EndOfFile) { return false; } if (_currentToken.Kind == RegexKind.BarToken) { return false; } if (_currentToken.Kind == RegexKind.CloseParenToken) { return consumeCloseParen; } return true; } private RegexExpressionNode ParsePrimaryExpressionAndQuantifiers(RegexExpressionNode lastExpression) { var current = ParsePrimaryExpression(lastExpression); if (current.Kind == RegexKind.SimpleOptionsGrouping) { // Simple options (i.e. "(?i-x)" can't have quantifiers attached to them). return current; } return _currentToken.Kind switch { RegexKind.AsteriskToken => ParseZeroOrMoreQuantifier(current), RegexKind.PlusToken => ParseOneOrMoreQuantifier(current), RegexKind.QuestionToken => ParseZeroOrOneQuantifier(current), RegexKind.OpenBraceToken => TryParseNumericQuantifier(current, _currentToken), _ => current, }; } private RegexExpressionNode TryParseLazyQuantifier(RegexQuantifierNode quantifier) { if (_currentToken.Kind != RegexKind.QuestionToken) { return quantifier; } // Whitespace allowed after the question and the next sequence element. return new RegexLazyQuantifierNode(quantifier, ConsumeCurrentToken(allowTrivia: true)); } private RegexExpressionNode ParseZeroOrMoreQuantifier(RegexPrimaryExpressionNode current) { // Whitespace allowed between the quantifier and the possible following ? or next sequence item. return TryParseLazyQuantifier(new RegexZeroOrMoreQuantifierNode(current, ConsumeCurrentToken(allowTrivia: true))); } private RegexExpressionNode ParseOneOrMoreQuantifier(RegexPrimaryExpressionNode current) { // Whitespace allowed between the quantifier and the possible following ? or next sequence item. return TryParseLazyQuantifier(new RegexOneOrMoreQuantifierNode(current, ConsumeCurrentToken(allowTrivia: true))); } private RegexExpressionNode ParseZeroOrOneQuantifier(RegexPrimaryExpressionNode current) { // Whitespace allowed between the quantifier and the possible following ? or next sequence item. return TryParseLazyQuantifier(new RegexZeroOrOneQuantifierNode(current, ConsumeCurrentToken(allowTrivia: true))); } private RegexExpressionNode TryParseNumericQuantifier( RegexPrimaryExpressionNode expression, RegexToken openBraceToken) { var start = _lexer.Position; if (!TryParseNumericQuantifierParts( out var firstNumberToken, out var commaToken, out var secondNumberToken, out var closeBraceToken)) { _currentToken = openBraceToken; _lexer.Position = start; return expression; } var quantifier = CreateQuantifier( expression, openBraceToken, firstNumberToken, commaToken, secondNumberToken, closeBraceToken); return TryParseLazyQuantifier(quantifier); } private static RegexQuantifierNode CreateQuantifier( RegexPrimaryExpressionNode expression, RegexToken openBraceToken, RegexToken firstNumberToken, RegexToken? commaToken, RegexToken? secondNumberToken, RegexToken closeBraceToken) { if (commaToken != null) { return secondNumberToken != null ? new RegexClosedNumericRangeQuantifierNode(expression, openBraceToken, firstNumberToken, commaToken.Value, secondNumberToken.Value, closeBraceToken) : (RegexQuantifierNode)new RegexOpenNumericRangeQuantifierNode(expression, openBraceToken, firstNumberToken, commaToken.Value, closeBraceToken); } return new RegexExactNumericQuantifierNode(expression, openBraceToken, firstNumberToken, closeBraceToken); } private bool TryParseNumericQuantifierParts( out RegexToken firstNumberToken, out RegexToken? commaToken, out RegexToken? secondNumberToken, out RegexToken closeBraceToken) { firstNumberToken = default; commaToken = null; secondNumberToken = null; closeBraceToken = default; var firstNumber = _lexer.TryScanNumber(); if (firstNumber == null) { return false; } firstNumberToken = firstNumber.Value; // Nothing allowed between {x,n} ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.CommaToken) { commaToken = _currentToken; var start = _lexer.Position; secondNumberToken = _lexer.TryScanNumber(); if (secondNumberToken == null) { // Nothing allowed between {x,n} ResetToPositionAndConsumeCurrentToken(start, allowTrivia: false); } else { var secondNumberTokenLocal = secondNumberToken.Value; // Nothing allowed between {x,n} ConsumeCurrentToken(allowTrivia: false); var val1 = (int)firstNumberToken.Value; var val2 = (int)secondNumberTokenLocal.Value; if (val2 < val1) { secondNumberTokenLocal = secondNumberTokenLocal.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Illegal_x_y_with_x_less_than_y, secondNumberTokenLocal.GetSpan())); secondNumberToken = secondNumberTokenLocal; } } } if (_currentToken.Kind != RegexKind.CloseBraceToken) { return false; } // Whitespace allowed between the quantifier and the possible following ? or next sequence item. closeBraceToken = ConsumeCurrentToken(allowTrivia: true); return true; } private void ResetToPositionAndConsumeCurrentToken(int position, bool allowTrivia) { _lexer.Position = position; ConsumeCurrentToken(allowTrivia); } private RegexPrimaryExpressionNode ParsePrimaryExpression(RegexExpressionNode lastExpression) { switch (_currentToken.Kind) { case RegexKind.DotToken: return ParseWildcard(); case RegexKind.CaretToken: return ParseStartAnchor(); case RegexKind.DollarToken: return ParseEndAnchor(); case RegexKind.BackslashToken: return ParseEscape(_currentToken, allowTriviaAfterEnd: true); case RegexKind.OpenBracketToken: return ParseCharacterClass(); case RegexKind.OpenParenToken: return ParseGrouping(); case RegexKind.CloseParenToken: return ParseUnexpectedCloseParenToken(); case RegexKind.OpenBraceToken: return ParsePossibleUnexpectedNumericQuantifier(lastExpression); case RegexKind.AsteriskToken: case RegexKind.PlusToken: case RegexKind.QuestionToken: return ParseUnexpectedQuantifier(lastExpression); default: return ParseText(); } } private RegexPrimaryExpressionNode ParsePossibleUnexpectedNumericQuantifier(RegexExpressionNode lastExpression) { // Native parser looks for something like {0,1} in a top level sequence and reports // an explicit error that that's not allowed. However, something like {0, 1} is fine // and is treated as six textual tokens. var openBraceToken = _currentToken.With(kind: RegexKind.TextToken); var start = _lexer.Position; if (TryParseNumericQuantifierParts( out _, out _, out _, out _)) { // Report that a numeric quantifier isn't allowed here. CheckQuantifierExpression(lastExpression, ref openBraceToken); } // Started with { but wasn't a numeric quantifier. This is totally legal and is just // a textual sequence. Restart, scanning this token as a normal sequence element. ResetToPositionAndConsumeCurrentToken(start, allowTrivia: true); return new RegexTextNode(openBraceToken); } private RegexPrimaryExpressionNode ParseUnexpectedCloseParenToken() { var token = _currentToken.With(kind: RegexKind.TextToken).AddDiagnosticIfNone( new EmbeddedDiagnostic(FeaturesResources.Too_many_close_parens, _currentToken.GetSpan())); // Technically, since an error occurred, we can do whatever we want here. However, // the spirit of the native parser is that top level sequence elements are allowed // to have trivia. So that's the behavior we mimic. ConsumeCurrentToken(allowTrivia: true); return new RegexTextNode(token); } private RegexPrimaryExpressionNode ParseText() { var token = ConsumeCurrentToken(allowTrivia: true); Debug.Assert(token.Value == null); // Allow trivia between this piece of text and the next sequence element return new RegexTextNode(token.With(kind: RegexKind.TextToken)); } private RegexPrimaryExpressionNode ParseEndAnchor() { // Allow trivia between this anchor and the next sequence element return new RegexAnchorNode(RegexKind.EndAnchor, ConsumeCurrentToken(allowTrivia: true)); } private RegexPrimaryExpressionNode ParseStartAnchor() { // Allow trivia between this anchor and the next sequence element return new RegexAnchorNode(RegexKind.StartAnchor, ConsumeCurrentToken(allowTrivia: true)); } private RegexPrimaryExpressionNode ParseWildcard() { // Allow trivia between the . and the next sequence element return new RegexWildcardNode(ConsumeCurrentToken(allowTrivia: true)); } private RegexGroupingNode ParseGrouping() { var start = _lexer.Position; // Check what immediately follows the (. If we have (? it is processed specially. // However, we do not treat (? the same as ( ? var openParenToken = ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.QuestionToken: return ParseGroupQuestion(openParenToken, _currentToken); default: // Wasn't (? just parse this as a normal group. _lexer.Position = start; return ParseSimpleGroup(openParenToken); } } private RegexToken ParseGroupingCloseParen() { switch (_currentToken.Kind) { case RegexKind.CloseParenToken: // Grouping completed normally. Allow trivia between it and the next sequence element. return ConsumeCurrentToken(allowTrivia: true); default: return CreateMissingToken(RegexKind.CloseParenToken).AddDiagnosticIfNone( new EmbeddedDiagnostic(FeaturesResources.Not_enough_close_parens, GetTokenStartPositionSpan(_currentToken))); } } private RegexSimpleGroupingNode ParseSimpleGroup(RegexToken openParenToken) => new( openParenToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); private RegexExpressionNode ParseGroupingEmbeddedExpression(RegexOptions embeddedOptions) { // Save and restore options when we go into, and pop out of a group node. var currentOptions = _options; _options = embeddedOptions; // We're parsing the embedded sequence inside the current group. As this is a sequence // we want to allow trivia between the current token we're on, and the first token // of the embedded sequence. ConsumeCurrentToken(allowTrivia: true); // When parsing out the sequence don't grab the close paren, that will be for our caller // to get. var expression = this.ParseAlternatingSequences(consumeCloseParen: false); _options = currentOptions; return expression; } private TextSpan GetTokenSpanIncludingEOF(RegexToken token) => token.Kind == RegexKind.EndOfFile ? GetTokenStartPositionSpan(token) : token.GetSpan(); private TextSpan GetTokenStartPositionSpan(RegexToken token) { return token.Kind == RegexKind.EndOfFile ? new TextSpan(_lexer.Text.Last().Span.End, 0) : new TextSpan(token.VirtualChars[0].Span.Start, 0); } private RegexGroupingNode ParseGroupQuestion(RegexToken openParenToken, RegexToken questionToken) { var optionsToken = _lexer.TryScanOptions(); if (optionsToken != null) { return ParseOptionsGroupingNode(openParenToken, questionToken, optionsToken.Value); } var afterQuestionPos = _lexer.Position; // Lots of possible options when we see (?. Look at the immediately following character // (without any allowed spaces) to decide what to parse out next. ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.LessThanToken: // (?<=...) or (?<!...) or (?<...>...) or (?<...-...>...) return ParseLookbehindOrNamedCaptureOrBalancingGrouping(openParenToken, questionToken); case RegexKind.SingleQuoteToken: // (?'...'...) or (?'...-...'...) return ParseNamedCaptureOrBalancingGrouping( openParenToken, questionToken, _currentToken); case RegexKind.OpenParenToken: // alternation construct (?(...) | ) return ParseConditionalGrouping(openParenToken, questionToken); case RegexKind.ColonToken: return ParseNonCapturingGroupingNode(openParenToken, questionToken); case RegexKind.EqualsToken: return ParsePositiveLookaheadGrouping(openParenToken, questionToken); case RegexKind.ExclamationToken: return ParseNegativeLookaheadGrouping(openParenToken, questionToken); case RegexKind.GreaterThanToken: return ParseAtomicGrouping(openParenToken, questionToken); default: if (_currentToken.Kind != RegexKind.CloseParenToken) { // Native parser reports "Unrecognized grouping construct", *except* for (?) openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_grouping_construct, openParenToken.GetSpan())); } break; } // (?) // Parse this as a normal group. The question will immediately error as it's a // quantifier not following anything. _lexer.Position = afterQuestionPos - 1; return ParseSimpleGroup(openParenToken); } private RegexConditionalGroupingNode ParseConditionalGrouping(RegexToken openParenToken, RegexToken questionToken) { var innerOpenParenToken = _currentToken; var afterInnerOpenParen = _lexer.Position; var captureToken = _lexer.TryScanNumberOrCaptureName(); if (captureToken == null) { return ParseConditionalExpressionGrouping(openParenToken, questionToken); } var capture = captureToken.Value; RegexToken innerCloseParenToken; if (capture.Kind == RegexKind.NumberToken) { // If it's a numeric group, it has to be immediately followed by a ) and the // numeric reference has to exist. // // That means that (?(4 ) is not treated as an embedded expression but as an // error. This is different from (?(a ) which will be treated as an embedded // expression, and different from (?(a) will be treated as an embedded // expression or capture group depending on if 'a' is a existing capture name. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.CloseParenToken) { innerCloseParenToken = _currentToken; if (!HasCapture((int)capture.Value)) { capture = capture.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Reference_to_undefined_group, capture.GetSpan())); } } else { innerCloseParenToken = CreateMissingToken(RegexKind.CloseParenToken); capture = capture.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Malformed, capture.GetSpan())); MoveBackBeforePreviousScan(); } } else { // If it's a capture name, it's ok if that capture doesn't exist. In that case we // will just treat this as an conditional expression. if (!HasCapture((string)capture.Value)) { _lexer.Position = afterInnerOpenParen; return ParseConditionalExpressionGrouping(openParenToken, questionToken); } // Capture name existed. For this to be a capture grouping it exactly has to // match (?(a) anything other than a close paren after the ) will make this // into a conditional expression. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind != RegexKind.CloseParenToken) { _lexer.Position = afterInnerOpenParen; return ParseConditionalExpressionGrouping(openParenToken, questionToken); } innerCloseParenToken = _currentToken; } // Was (?(name) or (?(num) and name/num was a legal capture name. Parse // this out as a conditional grouping. Because we're going to be parsing out // an embedded sequence, allow trivia before the first element. ConsumeCurrentToken(allowTrivia: true); var result = ParseConditionalGroupingResult(); return new RegexConditionalCaptureGroupingNode( openParenToken, questionToken, innerOpenParenToken, capture, innerCloseParenToken, result, ParseGroupingCloseParen()); } private bool HasCapture(int value) => _captureNumbersToSpan.ContainsKey(value); private bool HasCapture(string value) => _captureNamesToSpan.ContainsKey(value); private void MoveBackBeforePreviousScan() { if (_currentToken.Kind != RegexKind.EndOfFile) { // Move back to un-consume whatever we just consumed. _lexer.Position--; } } private RegexConditionalGroupingNode ParseConditionalExpressionGrouping( RegexToken openParenToken, RegexToken questionToken) { // Reproduce very specific errors the .NET regex parser looks for. Technically, // we would error out in these cases no matter what. However, it means we can // stringently enforce that our parser produces the same errors as the native one. // // Move back before the ( _lexer.Position--; if (_lexer.IsAt("(?#")) { var pos = _lexer.Position; var comment = _lexer.ScanComment(options: default); _lexer.Position = pos; if (comment.Value.Diagnostics.Length > 0) { openParenToken = openParenToken.AddDiagnosticIfNone(comment.Value.Diagnostics[0]); } else { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Alternation_conditions_cannot_be_comments, openParenToken.GetSpan())); } } else if (_lexer.IsAt("(?'")) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named, openParenToken.GetSpan())); } else if (_lexer.IsAt("(?<")) { if (!_lexer.IsAt("(?<!") && !_lexer.IsAt("(?<=")) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named, openParenToken.GetSpan())); } } // Consume the ( once more. ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.Kind == RegexKind.OpenParenToken); // Parse out the grouping that starts with the second open paren in (?( // this will get us to (?(...) var grouping = ParseGrouping(); // Now parse out the embedded expression that follows that. this will get us to // (?(...)... var result = ParseConditionalGroupingResult(); // Finally, grab the close paren and produce (?(...)...) return new RegexConditionalExpressionGroupingNode( openParenToken, questionToken, grouping, result, ParseGroupingCloseParen()); } private RegexExpressionNode ParseConditionalGroupingResult() { var currentOptions = _options; var result = this.ParseAlternatingSequences(consumeCloseParen: false); _options = currentOptions; result = CheckConditionalAlternation(result); return result; } private static RegexExpressionNode CheckConditionalAlternation(RegexExpressionNode result) { if (result is RegexAlternationNode topAlternation && topAlternation.Left is RegexAlternationNode) { return new RegexAlternationNode( topAlternation.Left, topAlternation.BarToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Too_many_bars_in_conditional_grouping, topAlternation.BarToken.GetSpan())), topAlternation.Right); } return result; } private RegexGroupingNode ParseLookbehindOrNamedCaptureOrBalancingGrouping( RegexToken openParenToken, RegexToken questionToken) { var start = _lexer.Position; // We have (?< Look for (?<= or (?<! var lessThanToken = ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.EqualsToken: return new RegexPositiveLookbehindGroupingNode( openParenToken, questionToken, lessThanToken, _currentToken, ParseGroupingEmbeddedExpression(_options | RegexOptions.RightToLeft), ParseGroupingCloseParen()); case RegexKind.ExclamationToken: return new RegexNegativeLookbehindGroupingNode( openParenToken, questionToken, lessThanToken, _currentToken, ParseGroupingEmbeddedExpression(_options | RegexOptions.RightToLeft), ParseGroupingCloseParen()); default: // Didn't have a lookbehind group. Parse out as (?<...> or (?<...-...> _lexer.Position = start; return ParseNamedCaptureOrBalancingGrouping(openParenToken, questionToken, lessThanToken); } } private RegexGroupingNode ParseNamedCaptureOrBalancingGrouping( RegexToken openParenToken, RegexToken questionToken, RegexToken openToken) { if (_lexer.Position == _lexer.Text.Length) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_grouping_construct, GetSpan(openParenToken, openToken))); } // (?<...>...) or (?<...-...>...) // (?'...'...) or (?'...-...'...) var captureToken = _lexer.TryScanNumberOrCaptureName(); if (captureToken == null) { // Can't have any trivia between the elements in this grouping header. ConsumeCurrentToken(allowTrivia: false); captureToken = CreateMissingToken(RegexKind.CaptureNameToken); if (_currentToken.Kind == RegexKind.MinusToken) { return ParseBalancingGrouping( openParenToken, questionToken, openToken, captureToken.Value); } else { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character, GetTokenSpanIncludingEOF(_currentToken))); // If we weren't at the end of the text, go back to before whatever character // we just consumed. MoveBackBeforePreviousScan(); } } var capture = captureToken.Value; if (capture.Kind == RegexKind.NumberToken && (int)capture.Value == 0) { capture = capture.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Capture_number_cannot_be_zero, capture.GetSpan())); } // Can't have any trivia between the elements in this grouping header. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.MinusToken) { // Have (?<...- parse out the balancing group form. return ParseBalancingGrouping( openParenToken, questionToken, openToken, capture); } var closeToken = ParseCaptureGroupingCloseToken(ref openParenToken, openToken); return new RegexCaptureGroupingNode( openParenToken, questionToken, openToken, capture, closeToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); } private RegexToken ParseCaptureGroupingCloseToken(ref RegexToken openParenToken, RegexToken openToken) { if ((openToken.Kind == RegexKind.LessThanToken && _currentToken.Kind == RegexKind.GreaterThanToken) || (openToken.Kind == RegexKind.SingleQuoteToken && _currentToken.Kind == RegexKind.SingleQuoteToken)) { return _currentToken; } if (_currentToken.Kind == RegexKind.EndOfFile) { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_grouping_construct, GetSpan(openParenToken, openToken))); } else { openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character, _currentToken.GetSpan())); // Rewind to where we were before seeing this bogus character. _lexer.Position--; } return CreateMissingToken( openToken.Kind == RegexKind.LessThanToken ? RegexKind.GreaterThanToken : RegexKind.SingleQuoteToken); } private RegexBalancingGroupingNode ParseBalancingGrouping( RegexToken openParenToken, RegexToken questionToken, RegexToken openToken, RegexToken firstCapture) { var minusToken = _currentToken; var secondCapture = _lexer.TryScanNumberOrCaptureName(); if (secondCapture == null) { // Invalid group name: Group names must begin with a word character ConsumeCurrentToken(allowTrivia: false); openParenToken = openParenToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character, GetTokenSpanIncludingEOF(_currentToken))); // If we weren't at the end of the text, go back to before whatever character // we just consumed. MoveBackBeforePreviousScan(); secondCapture = CreateMissingToken(RegexKind.CaptureNameToken); } var second = secondCapture.Value; CheckCapture(ref second); // Can't have any trivia between the elements in this grouping header. ConsumeCurrentToken(allowTrivia: false); var closeToken = ParseCaptureGroupingCloseToken(ref openParenToken, openToken); return new RegexBalancingGroupingNode( openParenToken, questionToken, openToken, firstCapture, minusToken, second, closeToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); } private void CheckCapture(ref RegexToken captureToken) { if (captureToken.IsMissing) { // Don't need to check for a synthesized error capture token. return; } if (captureToken.Kind == RegexKind.NumberToken) { var val = (int)captureToken.Value; if (!HasCapture(val)) { captureToken = captureToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Reference_to_undefined_group_number_0, val), captureToken.GetSpan())); } } else { var val = (string)captureToken.Value; if (!HasCapture(val)) { captureToken = captureToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Reference_to_undefined_group_name_0, val), captureToken.GetSpan())); } } } private RegexNonCapturingGroupingNode ParseNonCapturingGroupingNode(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); private RegexPositiveLookaheadGroupingNode ParsePositiveLookaheadGrouping(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options & ~RegexOptions.RightToLeft), ParseGroupingCloseParen()); private RegexNegativeLookaheadGroupingNode ParseNegativeLookaheadGrouping(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options & ~RegexOptions.RightToLeft), ParseGroupingCloseParen()); private RegexAtomicGroupingNode ParseAtomicGrouping(RegexToken openParenToken, RegexToken questionToken) => new( openParenToken, questionToken, _currentToken, ParseGroupingEmbeddedExpression(_options), ParseGroupingCloseParen()); private RegexGroupingNode ParseOptionsGroupingNode( RegexToken openParenToken, RegexToken questionToken, RegexToken optionsToken) { // Only (?opts:...) or (?opts) are allowed. After the opts must be a : or ) ConsumeCurrentToken(allowTrivia: false); switch (_currentToken.Kind) { case RegexKind.CloseParenToken: // Allow trivia after the options and the next element in the sequence. _options = GetNewOptionsFromToken(_options, optionsToken); return new RegexSimpleOptionsGroupingNode( openParenToken, questionToken, optionsToken, ConsumeCurrentToken(allowTrivia: true)); case RegexKind.ColonToken: return ParseNestedOptionsGroupingNode(openParenToken, questionToken, optionsToken); default: return new RegexSimpleOptionsGroupingNode( openParenToken, questionToken, optionsToken, CreateMissingToken(RegexKind.CloseParenToken).AddDiagnosticIfNone( new EmbeddedDiagnostic(FeaturesResources.Unrecognized_grouping_construct, openParenToken.GetSpan()))); } } private RegexNestedOptionsGroupingNode ParseNestedOptionsGroupingNode( RegexToken openParenToken, RegexToken questionToken, RegexToken optionsToken) => new( openParenToken, questionToken, optionsToken, _currentToken, ParseGroupingEmbeddedExpression(GetNewOptionsFromToken(_options, optionsToken)), ParseGroupingCloseParen()); private static bool IsTextChar(RegexToken currentToken, char ch) => currentToken.Kind == RegexKind.TextToken && currentToken.VirtualChars.Length == 1 && currentToken.VirtualChars[0].Value == ch; private static RegexOptions GetNewOptionsFromToken(RegexOptions currentOptions, RegexToken optionsToken) { var copy = currentOptions; var on = true; foreach (var ch in optionsToken.VirtualChars) { switch (ch.Value) { case '-': on = false; break; case '+': on = true; break; default: var newOption = OptionFromCode(ch); if (on) { copy |= newOption; } else { copy &= ~newOption; } break; } } return copy; } private static RegexOptions OptionFromCode(VirtualChar ch) { switch (ch.Value) { case 'i': case 'I': return RegexOptions.IgnoreCase; case 'm': case 'M': return RegexOptions.Multiline; case 'n': case 'N': return RegexOptions.ExplicitCapture; case 's': case 'S': return RegexOptions.Singleline; case 'x': case 'X': return RegexOptions.IgnorePatternWhitespace; default: throw new InvalidOperationException(); } } private RegexBaseCharacterClassNode ParseCharacterClass() { var openBracketToken = _currentToken; Debug.Assert(openBracketToken.Kind == RegexKind.OpenBracketToken); var caretToken = CreateMissingToken(RegexKind.CaretToken); var closeBracketToken = CreateMissingToken(RegexKind.CloseBracketToken); // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.CaretToken) { caretToken = _currentToken; } else { MoveBackBeforePreviousScan(); } // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); using var _1 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var builder); while (_currentToken.Kind != RegexKind.EndOfFile) { Debug.Assert(_currentToken.VirtualChars.Length == 1); if (_currentToken.Kind == RegexKind.CloseBracketToken && builder.Count > 0) { // Allow trivia after the character class, and whatever is next in the sequence. closeBracketToken = ConsumeCurrentToken(allowTrivia: true); break; } ParseCharacterClassComponents(builder); } // We wil commonly get tons of text nodes in a row. For example, the // regex `[abc]` will be three text nodes in a row. To help save on memory // try to merge that into one single text node. using var _2 = ArrayBuilder<RegexExpressionNode>.GetInstance(out var contents); MergeTextNodes(builder, contents); if (closeBracketToken.IsMissing) { closeBracketToken = closeBracketToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unterminated_character_class_set, GetTokenStartPositionSpan(_currentToken))); } var components = new RegexSequenceNode(contents.ToImmutable()); return caretToken.IsMissing ? (RegexBaseCharacterClassNode)new RegexCharacterClassNode(openBracketToken, components, closeBracketToken) : new RegexNegatedCharacterClassNode(openBracketToken, caretToken, components, closeBracketToken); } private void ParseCharacterClassComponents(ArrayBuilder<RegexExpressionNode> components) { var left = ParseSingleCharacterClassComponent(isFirst: components.Count == 0, afterRangeMinus: false); if (left.Kind == RegexKind.CharacterClassEscape || left.Kind == RegexKind.CategoryEscape || IsEscapedMinus(left)) { // \s or \p{Lu} or \- on the left of a minus doesn't start a range. If there is a following // minus, it's just treated textually. components.Add(left); return; } if (_currentToken.Kind == RegexKind.MinusToken && !_lexer.IsAt("]")) { // trivia is not allowed anywhere in a character class var minusToken = ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.OpenBracketToken) { components.Add(left); components.Add(ParseCharacterClassSubtractionNode(minusToken)); } else { // Note that behavior of parsing here changed in .net. See issue: // https://github.com/dotnet/corefx/issues/31786 // // We follow the latest behavior in .net which parses things correctly. var right = ParseSingleCharacterClassComponent(isFirst: false, afterRangeMinus: true); if (TryGetRangeComponentValue(left, out var leftCh) && TryGetRangeComponentValue(right, out var rightCh) && leftCh > rightCh) { minusToken = minusToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.x_y_range_in_reverse_order, minusToken.GetSpan())); } components.Add(new RegexCharacterClassRangeNode(left, minusToken, right)); } } else { components.Add(left); } } private static bool IsEscapedMinus(RegexNode node) => node is RegexSimpleEscapeNode simple && IsTextChar(simple.TypeToken, '-'); private bool TryGetRangeComponentValue(RegexExpressionNode component, out int ch) { // Don't bother examining the component if it has any errors already. This also means // we don't have to worry about running into invalid escape sequences and the like. if (!HasProblem(component)) { return TryGetRangeComponentValueWorker(component, out ch); } ch = default; return false; } private bool TryGetRangeComponentValueWorker(RegexNode component, out int ch) { switch (component.Kind) { case RegexKind.SimpleEscape: var escapeNode = (RegexSimpleEscapeNode)component; ch = MapEscapeChar(escapeNode.TypeToken.VirtualChars[0]).Value; return true; case RegexKind.ControlEscape: var controlEscape = (RegexControlEscapeNode)component; var controlCh = controlEscape.ControlToken.VirtualChars[0].Value; // \ca interpreted as \cA if (controlCh is >= 'a' and <= 'z') { controlCh -= (char)('a' - 'A'); } // The control characters have values mapping from the A-Z range to numeric // values 1-26. So, to map that, we subtract 'A' from the value (which would // give us 0-25) and then add '1' back to it. ch = controlCh - 'A' + 1; return true; case RegexKind.OctalEscape: ch = GetCharValue(((RegexOctalEscapeNode)component).OctalText, withBase: 8); return true; case RegexKind.HexEscape: ch = GetCharValue(((RegexHexEscapeNode)component).HexText, withBase: 16); return true; case RegexKind.UnicodeEscape: ch = GetCharValue(((RegexUnicodeEscapeNode)component).HexText, withBase: 16); return true; case RegexKind.PosixProperty: // When the native parser sees [:...:] it treats this as if it just saw '[' and skipped the // rest. ch = '['; return true; case RegexKind.Text: ch = ((RegexTextNode)component).TextToken.VirtualChars[0].Value; return true; case RegexKind.Sequence: var sequence = (RegexSequenceNode)component; #if DEBUG Debug.Assert(sequence.ChildCount > 0); for (int i = 0, n = sequence.ChildCount - 1; i < n; i++) { Debug.Assert(IsEscapedMinus(sequence.ChildAt(i).Node)); } #endif var last = sequence.ChildAt(sequence.ChildCount - 1).Node; if (IsEscapedMinus(last)) { break; } return TryGetRangeComponentValueWorker(last, out ch); } ch = default; return false; } private static int GetCharValue(RegexToken hexText, int withBase) { unchecked { var total = 0; foreach (var vc in hexText.VirtualChars) { total *= withBase; total += HexValue(vc); } return total; } } private static int HexValue(VirtualChar ch) { Debug.Assert(RegexLexer.IsHexChar(ch)); unchecked { var temp = ch.Value - '0'; if (temp is >= 0 and <= 9) return temp; temp = ch.Value - 'a'; if (temp is >= 0 and <= 5) return temp + 10; temp = ch.Value - 'A'; if (temp is >= 0 and <= 5) return temp + 10; } throw new InvalidOperationException(); } private bool HasProblem(RegexNodeOrToken component) { if (component.IsNode) { foreach (var child in component.Node) { if (HasProblem(child)) { return true; } } } else { var token = component.Token; if (token.IsMissing || token.Diagnostics.Length > 0) { return true; } foreach (var trivia in token.LeadingTrivia) { if (trivia.Diagnostics.Length > 0) { return true; } } } return false; } private RegexPrimaryExpressionNode ParseSingleCharacterClassComponent(bool isFirst, bool afterRangeMinus) { if (_currentToken.Kind == RegexKind.BackslashToken && _lexer.Position < _lexer.Text.Length) { var backslashToken = _currentToken; // trivia is not allowed anywhere in a character class, and definitely not between // a \ and the following character. ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.VirtualChars.Length == 1); var nextChar = _currentToken.VirtualChars[0]; switch (nextChar.Value) { case 'D': case 'd': case 'S': case 's': case 'W': case 'w': case 'p': case 'P': if (afterRangeMinus) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, nextChar), GetSpan(backslashToken, _currentToken))); } // move back before the character we just scanned. // trivia is not allowed anywhere in a character class. // The above list are character class and category escapes. ParseEscape can // handle both of those, so we just defer to it. _lexer.Position--; return ParseEscape(backslashToken, allowTriviaAfterEnd: false); case '-': // trivia is not allowed anywhere in a character class. // We just let the basic consumption code pull out a token for us, we then // convert that to text since we treat all characters after the - as text no // matter what. return new RegexSimpleEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: false).With(kind: RegexKind.TextToken)); default: // trivia is not allowed anywhere in a character class. // Note: it is very intentional that we're calling ParseCharEscape and not // ParseEscape. Normal escapes are not interpreted the same way inside a // character class. For example \b is not an anchor in a character class. // And things like \k'...' are not k-captures, etc. etc. _lexer.Position--; return ParseCharEscape(backslashToken, allowTriviaAfterEnd: false); } } if (!afterRangeMinus && !isFirst && _currentToken.Kind == RegexKind.MinusToken && _lexer.IsAt("[")) { // have a trailing subtraction. // trivia is not allowed anywhere in a character class return ParseCharacterClassSubtractionNode( ConsumeCurrentToken(allowTrivia: false)); } // From the .NET regex code: // This is code for Posix style properties - [:Ll:] or [:IsTibetan:]. // It currently doesn't do anything other than skip the whole thing! if (!afterRangeMinus && _currentToken.Kind == RegexKind.OpenBracketToken && _lexer.IsAt(":")) { var beforeBracketPos = _lexer.Position - 1; // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); var captureName = _lexer.TryScanCaptureName(); if (captureName.HasValue && _lexer.IsAt(":]")) { _lexer.Position += 2; var textChars = _lexer.GetSubPattern(beforeBracketPos, _lexer.Position); var token = CreateToken(RegexKind.TextToken, ImmutableArray<RegexTrivia>.Empty, textChars); // trivia is not allowed anywhere in a character class ConsumeCurrentToken(allowTrivia: false); return new RegexPosixPropertyNode(token); } else { // Reset to back where we were. // trivia is not allowed anywhere in a character class _lexer.Position = beforeBracketPos; ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.Kind == RegexKind.OpenBracketToken); } } // trivia is not allowed anywhere in a character class return new RegexTextNode( ConsumeCurrentToken(allowTrivia: false).With(kind: RegexKind.TextToken)); } private RegexPrimaryExpressionNode ParseCharacterClassSubtractionNode(RegexToken minusToken) { var charClass = ParseCharacterClass(); if (_currentToken.Kind is not RegexKind.CloseBracketToken and not RegexKind.EndOfFile) { minusToken = minusToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class, GetTokenStartPositionSpan(minusToken))); } return new RegexCharacterClassSubtractionNode(minusToken, charClass); } /// <summary> /// Parses out an escape sequence. Escape sequences are allowed in top level sequences /// and in character classes. In a top level sequence trivia will be allowed afterwards, /// but in a character class trivia is not allowed afterwards. /// </summary> private RegexEscapeNode ParseEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); // No spaces between \ and next char. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.EndOfFile) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Illegal_backslash_at_end_of_pattern, backslashToken.GetSpan())); return new RegexSimpleEscapeNode(backslashToken, CreateMissingToken(RegexKind.TextToken)); } Debug.Assert(_currentToken.VirtualChars.Length == 1); switch (_currentToken.VirtualChars[0].Value) { case 'b': case 'B': case 'A': case 'G': case 'Z': case 'z': return new RegexAnchorEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd)); case 'w': case 'W': case 's': case 'S': case 'd': case 'D': return new RegexCharacterClassEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd)); case 'p': case 'P': return ParseCategoryEscape(backslashToken, allowTriviaAfterEnd); } // Move back to after the backslash _lexer.Position--; return ParseBasicBackslash(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParseBasicBackslash(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); // No spaces between \ and next char. ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.EndOfFile) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Illegal_backslash_at_end_of_pattern, backslashToken.GetSpan())); return new RegexSimpleEscapeNode(backslashToken, CreateMissingToken(RegexKind.TextToken)); } Debug.Assert(_currentToken.VirtualChars.Length == 1); var ch = _currentToken.VirtualChars[0]; if (ch == 'k') { return ParsePossibleKCaptureEscape(backslashToken, allowTriviaAfterEnd); } if (ch.Value is '<' or '\'') { _lexer.Position--; return ParsePossibleCaptureEscape(backslashToken, allowTriviaAfterEnd); } if (ch.Value is >= '1' and <= '9') { _lexer.Position--; return ParsePossibleBackreferenceEscape(backslashToken, allowTriviaAfterEnd); } _lexer.Position--; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleBackreferenceEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); return HasOption(_options, RegexOptions.ECMAScript) ? ParsePossibleEcmascriptBackreferenceEscape(backslashToken, allowTriviaAfterEnd) : ParsePossibleRegularBackreferenceEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleEcmascriptBackreferenceEscape( RegexToken backslashToken, bool allowTriviaAfterEnd) { // Small deviation: Ecmascript allows references only to captures that precede // this position (unlike .NET which allows references in any direction). However, // because we don't track position, we just consume the entire back-reference. // // This is addressable if we add position tracking when we locate all the captures. Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); var start = _lexer.Position; var bestPosition = -1; var capVal = 0; while (_lexer.Position < _lexer.Text.Length && _lexer.Text[_lexer.Position] is var ch && (ch >= '0' && ch <= '9')) { unchecked { capVal *= 10; capVal += (ch.Value - '0'); } _lexer.Position++; if (HasCapture(capVal)) { bestPosition = _lexer.Position; } } if (bestPosition != -1) { var numberToken = CreateToken( RegexKind.NumberToken, ImmutableArray<RegexTrivia>.Empty, _lexer.GetSubPattern(start, bestPosition)).With(value: capVal); ResetToPositionAndConsumeCurrentToken(bestPosition, allowTrivia: allowTriviaAfterEnd); return new RegexBackreferenceEscapeNode(backslashToken, numberToken); } _lexer.Position = start; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleRegularBackreferenceEscape( RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); var start = _lexer.Position; var numberToken = _lexer.TryScanNumber().Value; var capVal = (int)numberToken.Value; if (HasCapture(capVal) || capVal <= 9) { CheckCapture(ref numberToken); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexBackreferenceEscapeNode(backslashToken, numberToken); } _lexer.Position = start; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } private RegexEscapeNode ParsePossibleCaptureEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); Debug.Assert(_lexer.Text[_lexer.Position].Value is '<' or '\''); var afterBackslashPosition = _lexer.Position; ScanCaptureParts(allowTriviaAfterEnd, out var openToken, out var capture, out var closeToken); if (openToken.IsMissing || capture.IsMissing || closeToken.IsMissing) { _lexer.Position = afterBackslashPosition; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } return new RegexCaptureEscapeNode( backslashToken, openToken, capture, closeToken); } private RegexEscapeNode ParsePossibleKCaptureEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { var typeToken = _currentToken; var afterBackslashPosition = _lexer.Position - @"k".Length; ScanCaptureParts(allowTriviaAfterEnd, out var openToken, out var capture, out var closeToken); if (openToken.IsMissing) { backslashToken = backslashToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Malformed_named_back_reference, GetSpan(backslashToken, typeToken))); return new RegexSimpleEscapeNode(backslashToken, typeToken.With(kind: RegexKind.TextToken)); } if (capture.IsMissing || closeToken.IsMissing) { // Native parser falls back to normal escape scanning, if it doesn't see a capture, // or close brace. For normal .NET regexes, this will then fail later (as \k is not // a legal escape), but will succeed for ecmascript regexes. _lexer.Position = afterBackslashPosition; return ParseCharEscape(backslashToken, allowTriviaAfterEnd); } return new RegexKCaptureEscapeNode( backslashToken, typeToken, openToken, capture, closeToken); } private void ScanCaptureParts( bool allowTriviaAfterEnd, out RegexToken openToken, out RegexToken capture, out RegexToken closeToken) { openToken = CreateMissingToken(RegexKind.LessThanToken); capture = CreateMissingToken(RegexKind.CaptureNameToken); closeToken = CreateMissingToken(RegexKind.GreaterThanToken); // No trivia allowed in <cap> or 'cap' ConsumeCurrentToken(allowTrivia: false); if (_lexer.Position < _lexer.Text.Length && (_currentToken.Kind == RegexKind.LessThanToken || _currentToken.Kind == RegexKind.SingleQuoteToken)) { openToken = _currentToken; } else { return; } var captureToken = _lexer.TryScanNumberOrCaptureName(); capture = captureToken == null ? CreateMissingToken(RegexKind.CaptureNameToken) : captureToken.Value; // No trivia allowed in <cap> or 'cap' ConsumeCurrentToken(allowTrivia: false); closeToken = CreateMissingToken(RegexKind.GreaterThanToken); if (!capture.IsMissing && ((openToken.Kind == RegexKind.LessThanToken && _currentToken.Kind == RegexKind.GreaterThanToken) || (openToken.Kind == RegexKind.SingleQuoteToken && _currentToken.Kind == RegexKind.SingleQuoteToken))) { CheckCapture(ref capture); closeToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); } } private RegexEscapeNode ParseCharEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] == '\\'); // no trivia between \ and the next char ConsumeCurrentToken(allowTrivia: false); Debug.Assert(_currentToken.VirtualChars.Length == 1); var ch = _currentToken.VirtualChars[0]; if (ch.Value is >= '0' and <= '7') { _lexer.Position--; var octalDigits = _lexer.ScanOctalCharacters(_options); Debug.Assert(octalDigits.VirtualChars.Length > 0); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexOctalEscapeNode(backslashToken, octalDigits); } switch (ch.Value) { case 'a': case 'b': case 'e': case 'f': case 'n': case 'r': case 't': case 'v': return new RegexSimpleEscapeNode( backslashToken, ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd)); case 'x': return ParseHexEscape(backslashToken, allowTriviaAfterEnd); case 'u': return ParseUnicodeEscape(backslashToken, allowTriviaAfterEnd); case 'c': return ParseControlEscape(backslashToken, allowTriviaAfterEnd); default: var typeToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd).With(kind: RegexKind.TextToken); if (!HasOption(_options, RegexOptions.ECMAScript) && RegexCharClass.IsWordChar(ch)) { typeToken = typeToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Unrecognized_escape_sequence_0, ch), typeToken.GetSpan())); } return new RegexSimpleEscapeNode(backslashToken, typeToken); } } private RegexEscapeNode ParseUnicodeEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { var typeToken = _currentToken; var hexChars = _lexer.ScanHexCharacters(4); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexUnicodeEscapeNode(backslashToken, typeToken, hexChars); } private RegexEscapeNode ParseHexEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { var typeToken = _currentToken; var hexChars = _lexer.ScanHexCharacters(2); ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return new RegexHexEscapeNode(backslashToken, typeToken, hexChars); } private RegexControlEscapeNode ParseControlEscape(RegexToken backslashToken, bool allowTriviaAfterEnd) { // Nothing allowed between \c and the next char var typeToken = ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind == RegexKind.EndOfFile) { typeToken = typeToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Missing_control_character, typeToken.GetSpan())); return new RegexControlEscapeNode(backslashToken, typeToken, CreateMissingToken(RegexKind.TextToken)); } Debug.Assert(_currentToken.VirtualChars.Length == 1); var ch = _currentToken.VirtualChars[0].Value; unchecked { // From: https://github.com/dotnet/corefx/blob/80e220fc7009de0f0611ee6b52d4d5ffd25eb6c7/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs#L1450 // Note: Roslyn accepts a control escape that current .NET parser does not. // Specifically: \c[ // // It is a bug that the .NET parser does not support this construct. The bug was // reported at: https://github.com/dotnet/corefx/issues/26501 and was fixed for // CoreFx with https://github.com/dotnet/corefx/commit/80e220fc7009de0f0611ee6b52d4d5ffd25eb6c7 // // Because it was a bug, we follow the correct behavior. That means we will not // report a diagnostic for a Regex that someone might run on a previous version of // .NET that ends up throwing at runtime. That's acceptable. Our goal is to match // the latest .NET 'correct' behavior. Not intermediary points with bugs that have // since been fixed. // \ca interpreted as \cA if (ch is >= 'a' and <= 'z') { ch -= (char)('a' - 'A'); } if (ch is >= '@' and <= '_') { var controlToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd).With(kind: RegexKind.TextToken); return new RegexControlEscapeNode(backslashToken, typeToken, controlToken); } else { typeToken = typeToken.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Unrecognized_control_character, _currentToken.GetSpan())); // Don't consume the bogus control character. return new RegexControlEscapeNode(backslashToken, typeToken, CreateMissingToken(RegexKind.TextToken)); } } } private RegexEscapeNode ParseCategoryEscape(RegexToken backslash, bool allowTriviaAfterEnd) { Debug.Assert(_lexer.Text[_lexer.Position - 1] is var ch && (ch == 'P' || ch == 'p')); var typeToken = _currentToken; var start = _lexer.Position; if (!TryGetCategoryEscapeParts( allowTriviaAfterEnd, out var openBraceToken, out var categoryToken, out var closeBraceToken, out var message)) { ResetToPositionAndConsumeCurrentToken(start, allowTrivia: allowTriviaAfterEnd); typeToken = typeToken.With(kind: RegexKind.TextToken).AddDiagnosticIfNone(new EmbeddedDiagnostic( message, GetSpan(backslash, typeToken))); return new RegexSimpleEscapeNode(backslash, typeToken); } return new RegexCategoryEscapeNode(backslash, typeToken, openBraceToken, categoryToken, closeBraceToken); } private bool TryGetCategoryEscapeParts( bool allowTriviaAfterEnd, out RegexToken openBraceToken, out RegexToken categoryToken, out RegexToken closeBraceToken, out string message) { openBraceToken = default; categoryToken = default; closeBraceToken = default; message = null; if (_lexer.Text.Length - _lexer.Position < "{x}".Length) { message = FeaturesResources.Incomplete_character_escape; return false; } // no whitespace in \p{x} ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind != RegexKind.OpenBraceToken) { message = FeaturesResources.Malformed_character_escape; return false; } openBraceToken = _currentToken; var category = _lexer.TryScanEscapeCategory(); // no whitespace in \p{x} ConsumeCurrentToken(allowTrivia: false); if (_currentToken.Kind != RegexKind.CloseBraceToken) { message = FeaturesResources.Incomplete_character_escape; return false; } if (category == null) { message = FeaturesResources.Unknown_property; return false; } categoryToken = category.Value; closeBraceToken = ConsumeCurrentToken(allowTrivia: allowTriviaAfterEnd); return true; } private RegexTextNode ParseUnexpectedQuantifier(RegexExpressionNode lastExpression) { // This is just a bogus element in the higher level sequence. Allow trivia // after this to abide by the spirit of the native parser. var token = ConsumeCurrentToken(allowTrivia: true); CheckQuantifierExpression(lastExpression, ref token); return new RegexTextNode(token.With(kind: RegexKind.TextToken)); } private static void CheckQuantifierExpression(RegexExpressionNode current, ref RegexToken token) { if (current == null || current.Kind == RegexKind.SimpleOptionsGrouping) { token = token.AddDiagnosticIfNone(new EmbeddedDiagnostic( FeaturesResources.Quantifier_x_y_following_nothing, token.GetSpan())); } else if (current is RegexQuantifierNode or RegexLazyQuantifierNode) { token = token.AddDiagnosticIfNone(new EmbeddedDiagnostic( string.Format(FeaturesResources.Nested_quantifier_0, token.VirtualChars.First()), token.GetSpan())); } } } }
-1